Unlock the Secret of Armstrong Numbers
The Magic of Armstrong Numbers
A positive integer is considered an Armstrong number of order n if the sum of the cubes of its individual digits is equal to the number itself. Sounds intriguing, doesn’t it? Let’s take a closer look.
The 3-Digit Armstrong Number
In the case of a 3-digit Armstrong number, the sum of the cubes of each digit must equal the number itself. For instance, 153 is an Armstrong number because 1³ + 5³ + 3³ = 153.
int num = 153;
int sum = 0;
while (num!= 0) {
int digit = num % 10;
sum += pow(digit, 3);
num /= 10;
}
if (sum == 153) {
cout << "153 is an Armstrong number." << endl;
}
Scaling Up to n Digits
But what if we want to check Armstrong numbers with more than 3 digits? We can modify our program to calculate the number of digits in the entered number and store it in a variable n. Then, we use the pow() function to compute the power of individual digits in each iteration of the while loop.
int num, n;
cout << "Enter a number: ";
cin >> num;
n = to_string(num).length();
int sum = 0;
int temp = num;
while (temp!= 0) {
int digit = temp % 10;
sum += pow(digit, n);
temp /= 10;
}
if (sum == num) {
cout << num << " is an Armstrong number." << endl;
} else {
cout << num << " is not an Armstrong number." << endl;
}
Taking it to the Next Level
Now that you’ve mastered the art of checking Armstrong numbers, why not take it a step further? Try writing a program to display Armstrong numbers between two intervals. The possibilities are endless!
- Write a program to find Armstrong numbers between 100 and 999.
- Modify the program to work with different intervals.
- Explore other properties of Armstrong numbers.
Get Ready to Code
With these concepts under your belt, you’re ready to dive into the world of C++ programming and create your own Armstrong number-checking program. So, what are you waiting for? Start coding today!
Learn more about C++ programming