C++ Program To Find Armstrong Numbers Between Two Integers
A positive integer with digits a, b, c, d… is called an Armstrong number of order n if following condition is satisfied.Â
abcd... = an + bn + cn + dn +...
153 = 1*1*1 + 5*5*5 + 3*3*3
= 1 + 125 + 27
= 153
Therefore, 153 is an Armstrong number.
Examples:
Input: 100 400
Output: 153 370 371
Explanation: 100 and 400 are given
two integers.(interval)
153 = 1*1*1 + 5*5*5 + 3*3*3
= 1 + 125 + 27
= 153
370 = 3*3*3 + 7*7*7 + 0
= 27 + 343
= 370
371 = 3*3*3 + 7*7*7 + 1*1*1
= 27 + 343 +1
= 371
The approach implemented below is simple. We traverse through all numbers in given range. For every number, we first count number of digits in it. Let the number of digits in current number be n. Them we find sum of n-th power of all digits. If sum is equal to i, we print the number.Â
C++
#include <bits/stdc++.h>
using namespace std;
void findArmstrong( int low, int high)
{
for ( int i = low+1; i < high; ++i)
{
int x = i;
int n = 0;
while (x != 0)
{
x /= 10;
++n;
}
int pow_sum = 0;
x = i;
while (x != 0)
{
int digit = x % 10;
pow_sum += pow (digit, n);
x /= 10;
}
if (pow_sum == i)
cout << i << " " ;
}
}
int main()
{
int num1 = 100;
int num2 = 400;
findArmstrong(num1, num2);
cout << '' ;
return 0;
}
|
Output:
153 370 371
Last Updated :
16 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...