C++ Armstrong Number Program
An Armstrong number equals the sum of its digits, each raised to the power of the number of digits. For example 153 = 1^3 + 5^3 + 3^3.
Program
#include <iostream>
#include <string>
int power(int base, int exponent) {
int result = 1;
for (int i = 0; i < exponent; i++) result *= base;
return result;
}
bool is_armstrong(int number) {
int digits = static_cast<int>(std::to_string(number).size());
int sum = 0, n = number;
while (n > 0) {
sum += power(n % 10, digits);
n /= 10;
}
return sum == number;
}
int main() {
std::cout << std::boolalpha << is_armstrong(153) << ' ' << is_armstrong(154) << ' ' << is_armstrong(9474) << '\n';
std::cout << "Armstrong numbers up to 1000: ";
for (int i = 1; i <= 1000; i++) {
if (is_armstrong(i)) std::cout << i << ' ';
}
std::cout << '\n';
}
Output
true false true
Armstrong numbers up to 1000: 1 2 3 4 5 6 7 8 9 153 370 371 407
How it works
std::to_string(number).size()counts the digits.- The loop takes the last digit with
% 10and adds its power. - We wrote our own integer
power, becausestd::powworks with decimals and can give a small rounding error.
Related: C++ while Loop.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |