Print Armstrong Numbers Between Two Integers in C++
Mathematics and programming when combined make a very deadly combination. As the ability to solve complex mathematical questions in itself is a great deal. But when one has to do the same thing by writing up a code, things get somewhat more complicated. Not to mention the language your coding in also determines whether it’s going to be easy to difficult. Well, Armstrong numbers are very well known in the mathematical world. Therefore today we’re going to write a program to print Armstrong Numbers Between Two Integers in C++.
What are Armstrong Numbers?
- Let us consider Number
X
withN
being the no digits inX. Then
X will be said as the Armstrong number if the sum of each digit of
X
is raised with orderN
equals toX
itself.
- Eg: 153 is the Armstrong Number.
- Therefore,
1 * 1 * 1 + 5 * 5 * 5 + 3 * 3 * 3 = 153
Also Read: Reverse A String in C++ using reverse()
What’s The Approach?
- We’ll
iterate a for loop
whereLow
andHigh
will determine the range of integers we’ll have to traverse.
- For each integer in the range, we will
Find The Number Of Digits
(N
) so that we can determine the order.
- Once we find the order, then for each digit (
R
) we will computeR
N After that, we will perform the addition of the computed values.
- If the computed addition equals iterative variable
i
of the for loop we’ll print it, otherwise, we’ll pass.
C++ Program To Print Armstrong Numbers Between Two Integers
Input:
num1 = 100
num2 = 400
Output:
153 370 371
// CPP program to find Armstrong numbers in a range #include <bits/stdc++.h> using namespace std; // Prints Armstrong Numbers in the given range void findArmstrong(int low, int high) { for (int i = low+1; i < high; ++i) { // number of digits calculation int x = i; int n = 0; while (x != 0) { x /= 10; ++n; } // compute sum of nth power of // its digits int pow_sum = 0; x = i; while (x != 0) { int digit = x % 10; pow_sum += pow(digit, n); x /= 10; } // checks if number i is equal to the // sum of nth power of its digits if (pow_sum == i) cout << i << " "; } } // Driver code int main() { int num1 = 100; int num2 = 400; findArmstrong(num1, num2); cout << '\n'; return 0; }