C++ How To Check if a Number Is an Armstrong Number
Check if a Number Is an Armstrong Number
An Armstrong number is equal to the sum of its digits, where each digit is raised to the power of the number of digits. For example, 153 = 13 + 53 + 33:
Example
int number = 153;
int digits = to_string(number).length();
int sum = 0;
int temp = number;
while (temp > 0) {
int digit = temp % 10;
int power = 1;
for (int i = 0; i < digits; i++) {
power *= digit;
}
sum += power;
temp /= 10;
}
if (sum == number) {
cout << number << " is an Armstrong number";
} else {
cout << number << " is not an Armstrong number";
}
Explanation:to_string(number).length() counts the digits (3).
For each digit, the inner loop calculates the digit to the power of 3, and adds it to sum.
1 + 125 + 27 is 153, which is the same as the number.
Related Pages
C++ Convert Strings and Numbers