- 0
Notifications Mark All Read
No New notification
- Login
- Get Prime
Program to First N Strong Numbers in Java
First N Strong Numbers in Java
Here, in this page we will discuss the program to find first N strong numbers in Java. We are given with the value of N and need to print the first N strong numbers.
Strong Number
Strong number is a special number whose sum of the factorial of digits is equal to the original number.
Algorithm :
- Declare a variable count = 0, that will count the number of strong numbers founded.
- Run a loop till count!=N
- And check if the number x is strong number or not.
- To check a number is strong or not,
- Store the factorial for digits 0 to 9 in an array.
- Run a loop till the number is greater than 0, set
- Sum = sum + (n%10)!.
- At last check if(sum==n)
- If yes then print the corresponding number and increase the value of count by 1,
- Else check for the next number.
Time and Space Complexity :
- Time Complexity : O(n)
- Space Complexity : O(1)
Code in Java
Run
class Main{ static int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 }; public static boolean isStrong(int N) { String num = Integer.toString(N); int sum = 0; for (int i = 0; i < num.length(); i++) { sum += factorial[Integer.parseInt(num.charAt(i) + "")]; } return sum == N; } public static void printStrongNumbers(int N) { int x = 1, count = 0; while(count != N){ if (isStrong(x)) { System.out.print(x + " "); count++; } x++; } } // Driver Code public static void main(String[] args) { int N = 3; // Function Call printStrongNumbers(N); } }
Output
1 2 145
Login/Signup to comment