C Program to Check If a Number is an Amstrong Number

Amstrong number

C program to check if a number is an amstrong number has been shown here. A positive integer of order n is called an amstrong number if the sum of each digit to the power n is equal to that number.


For example, 153 and 1634 are amstrong numbers as $153 = 1^3 + 5^3 + 3^3$ and $1634 = 1^4 + 6^4 + 3^4 + 4^4$.


The algorithm, pseudocode and time complexity of the program have been shown below.







1. Algorithm to check if a number is an amstrong number


1. Take input of a positive number n.

2. Calculate d, the total no of digit of n

3. Extract each digit $p_i$ and perform sum = $\sum_{i=1}^d p_i ^d $

4. Check If sum == n

5. If step 4 is true, then display n as an amstrong number

6. If step 4 is false, then display n as not an amstrong number




2. Pseudocode to check if a number is an amstrong number


Input : A postive number $n$ as input

Output : $n$ is an amstrong number or not an amstrong number

1. Procedure checkAmstrong($n$):

2. $t \leftarrow n$:

3. $sum \leftarrow 0$:

4. Count $d$, the total no of digits in $n$

5. Repeat until $t != 0$

6. $r \leftarrow t \mod 10$

7. $sum \leftarrow sum + r^d$

8. $t \leftarrow t / 10$

9. If $sum \mod n$ == 0:

10. Return "Amstrong number"

11. Else:

12. Return "Not an amstrong number"

13. End Procedure





3. Time complexity to check if a number is an amstrong number


Time Complexity: O(log(n))

Where log(n) is the total no of digits of the input number n.





4. C Program & output to check if a number is an amstrong number

Code has been copied
/******************************
    alphabetacoder.com
C program to check if a number 
is an amstrong number or not
*******************************/

#include <stdio.h>
#include <math.h>

int main() {
    // declare variables
    int n, d = 0, t, r, sum = 0;

    // take input of the number
    printf("Enter the number = ");
    scanf("%d", & n);

    // copy value
    t = n;
    // calculate the number of digit 
    while (t != 0) {
        d++;
        t = t / 10;
    }

    // copy value
    t = n;
    // find the sum of digits each to the power d
    while (t != 0) {
        r = t % 10;
        sum = sum + pow(r, d);
        t = t / 10;
    }

    //check if input number is amstrong or not
    if (n == sum)
        printf("%d is an amstrong number!", n);
    else
        printf("%d is not an amstrong number!", n);

    return 0;
}

Output


Case 1:

Enter the number = 153

153 is an amstrong number!


Case 2:

Enter the number = 5

5 is an amstrong number!


Case 3:

Enter the number = 50

50 is not an amstrong number!