Find the numbers that equal the sum of their digits, each raised to the number of digits.
What to build
A problem split across three small functions.
Requirements
- A number is an Armstrong number if the sum of its digits, each raised to the power of how many digits it has, equals the number. For example, 153 = 1 + 125 + 27.
- Read
aandb. - Print each Armstrong number from
atob, separated by single spaces, ornone.
Input
One line with two whole numbers.
Output
One line.
Constraints
1 is at most a, a is at most b, and b is at most 100000.
Example
Input:
100 200
Output:
153
Why it works
Each small function can be checked on its own, so the final test is one clear line. Trying to do it all in main would need three nested loops.
Examples
Example 1 · Input
100 200
Expected output
153
Example 2 · Input
1 9
Expected output
1 2 3 4 5 6 7 8 9
Hints
Hint 1
Write a function that counts the digits of a number.
Hint 2
Write a function for a whole-number power.
Hint 3
A third function adds each digit raised to the number of digits.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int count_digits(int n) {
int count = 0;
while (n > 0) {
count++;
n /= 10;
}
return count;
}
int power(int base, int exp) {
int result = 1;
for (int i = 0; i < exp; i++) {
result *= base;
}
return result;
}
int is_armstrong(int n) {
int digits = count_digits(n);
int sum = 0;
for (int m = n; m > 0; m /= 10) {
sum += power(m % 10, digits);
}
return sum == n;
}
int main(void) {
int a, b;
scanf("%d %d", &a, &b);
int found = 0;
for (int n = a; n <= b; n++) {
if (is_armstrong(n)) {
printf(found ? " %d" : "%d", n);
found = 1;
}
}
printf(found ? "\n" : "none\n");
return 0;
}