Answer: An Armstrong number with \(n\) digits equals the sum of each digit raised to the power \(n\) (for example \(153 = 1^3 + 5^3 + 3^3\) and \(1634 = 1^4 + 6^4 + 3^4 + 4^4\)).
Logic
- Count the digits \(n\) of the number.
- Take each digit with % 10, raise it to the power \(n\) and add to sum.
- If sum equals the original number, it is an Armstrong number.
Using cubes for every number works only for 3-digit numbers; counting the digits first makes the program correct for 1-digit numbers (all are Armstrong), 4-digit numbers like 1634, and so on.
Program
#include <stdio.h>
int main()
{
int num, temp, digit, n = 0, sum = 0, power, i;
printf("Enter a positive integer: ");
scanf("%d", &num);
/* step 1: count the digits */
temp = num;
do {
n++;
temp = temp / 10;
} while (temp != 0);
/* step 2: add each digit raised to the power n */
temp = num;
while (temp != 0) {
digit = temp % 10;
power = 1;
for (i = 1; i <= n; i++)
power = power * digit;
sum = sum + power;
temp = temp / 10;
}
if (sum == num)
printf("%d is an Armstrong number\n", num);
else
printf("%d is not an Armstrong number\n", num);
return 0;
}Sample runs (gcc)
Enter a positive integer: 153
153 is an Armstrong number
Enter a positive integer: 1634
1634 is an Armstrong number
Enter a positive integer: 5
5 is an Armstrong number
Enter a positive integer: 123
123 is not an Armstrong number