Armstrong number is also called narcissistic or pluperfect number. It is number whose sum of digits each raised to the power of its own number of digits is equal to the given number.
Lets say if a number has n digits d1d2d3…dn then to be Armstrong number following condition should be satisfied
d1d2d3…dn = d1n + d2n + d3n + …….+ dnn
153 has 3 digits if we calculate sum of digits raised to the number of digits which means 1 + 5 +3 is equal to 153
Similarly, 9474 has 4 digits if we calculate sum of digits raised to the number of digits which means 9 + 4 + 7 + 4 is equal to 9474
#include <stdio.h>
#include <math.h>
int main() {
int n, sum = 0, rem, temp;
printf("Enter any number: ");
scanf("%d", &n);
temp = n;
while (n != 0) {
rem = n % 10;
sum=sum + pow(rem, 3) ;
n=n/10;
}
if (temp==sum) {
printf("%d is armstrong", temp);
} else {
printf("%d is not Armstrong”, temp);
}
return 0;
}
The above program only checks the 3 digit number is Armstrong number or not, but in reality Armstrong number can be of any digit by definition. So to check whether the given number of any digits is Armstrong or not we can write following C program.
The logic behind this is almost similar, we need to replace 3 in pow(rem, 3) by the number or digits. But we don’t know the number of digits. So, we need to calculate the number of digits before while loop by using another loop
#include <stdio.h>
#include <math.h>
int main() {
int n, sum = 0, rem, temp1, temp2, count = 0;
printf("Enter any number: ");
scanf("%d", &n);
temp1 = n;
temp2 = n;
while (n != 0) {
n=n/10;
count ++;
}
// n becomes 0 here so we use temp1 instead of n and count instead of 3
while (temp1 != 0) {
rem = temp1 % 10;
sum=sum + pow(rem, count) ;
temp1=temp1/10;
}
// temp1 and n are both 0 here so we use temp 2 here instead do temp
if (temp2==sum) {
printf("%d is armstrong", temp2);
} else {
printf("%d is not Armstrong”, temp2);
}
return 0;
}
Learn C programming from scratch