A positive integer is called an Armstrong number (of order n) if
abcd... = an + bn + cn + dn +
In the case of an Armstrong number of 3 digits, the sum of cubes of each digit is equal to the number itself. For example, 153 is an Armstrong number because
153 = 1*1*1 + 5*5*5 + 3*3*3
Check Armstrong Number of three digits
#include <stdio.h>
int main() {
int num, originalNum, remainder, result = 0;
printf("Enter a three-digit integer: ");
scanf("%d", &num);
originalNum = num;
while (originalNum != 0) {
// remainder contains the last digit
remainder = originalNum % 10;
result += remainder * remainder * remainder;
// removing last digit from the orignal number
originalNum /= 10;
}
if (result == num)
printf("%d is an Armstrong number.", num);
else
printf("%d is not an Armstrong number.", num);
return 0;
}
Output
Enter a three-digit integer: 371 371 is an Armstrong number.
Check Armstrong Number of n digits
#include <stdio.h>
int main() {
unsigned long long int num, originalNum, remainder, n = 0;
unsigned long long int result = 0;
printf("Enter an integer: ");
scanf("%llu", &num);
originalNum = num;
// store the number of digits of num in n
while (originalNum != 0) {
originalNum /= 10;
++n;
}
originalNum = num;
while (originalNum != 0) {
remainder = originalNum % 10;
// calculate remainder^n
unsigned long long int power = 1;
for (unsigned long long int i = 0; i < n; i++) {
power *= remainder;
}
result += power;
originalNum /= 10;
}
// if num is equal to result, the number is an Armstrong number
if (result == num)
printf("%llu is an Armstrong number.\n", num);
else
printf("%llu is not an Armstrong number.\n", num);
return 0;
}
Output
Enter an integer: 1634 1634 is an Armstrong number.
In this program, the number of digits of an integer is calculated first and stored in n. And, we compute the power of individual digits in each iteration of the second for loop.
