Print The First n strong Numbers in C++
First n strong Numbers
Today in this page we will be discussing the code to print First n strong Numbers in C++ programming language.
Strong number is a special number whose sum of the factorial of digits is equal to the original number.
For Example: 145 is strong number. Since, 1! + 4! + 5! = 145.
The idea is to iterate from (1, N) and check if any number between the range is a strong number or not. If yes then print the corresponding number, else we need to check for the next number.
Let’s understand this with help of some examples.
Input: N = 100
Output: 1 2 145
Explanation:
Only 1, 2 and 145 are the strong numbers from 1 to 100 because
1! = 1,
2! = 2, and
(1! + 4! + 5!) = 145
First N Strong Numbers C++ Code
Run
#include <bits/stdc++.h>
int factorial[] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
bool isStrong(int N) {
string num = to_string(N);
int sum = 0;
for (int i = 0; i < num.length(); i++) {
sum += factorial[num[i] - '0'];
}
return sum == N;
}
void printStrongNumbers(int N) {
for (int i = 1; i <= N; i++) {
if (isStrong(i)) {
cout << i << " ";
}
}
}
int main() {
// Given number
int N = 200;
cout << "All Strong numbers less than or equal to N: "
printStrongNumbers(N);
return 0;
}all Strong numbers less than or equal to N: 1 2 145

Login/Signup to comment