- 0
Notifications Mark All Read
- Login
- Get Prime
Program to find Strong Numbers in a Given Range in Java
Strong Number in a Given Range in Java
Here, in this page we will discuss the program to find Strong Number in a Given Range in Java. We are given with two values and need to print the strong numbers between the given range.
Strong Number
Strong number is a special number whose sum of the factorial of digits is equal to the original number.
Example :
Input :
L = 1
R = 1000
Output :
1 2 145
Explanation :
Only 1, 2 and 145 are the strong numbers from 1 to 1000 because
1! = 1,
2! = 2, and
(1! + 4! + 5!) = 145
L = 1
R = 1000
Output :
1 2 145
Explanation :
Only 1, 2 and 145 are the strong numbers from 1 to 1000 because
1! = 1,
2! = 2, and
(1! + 4! + 5!) = 145
Algorithm :
- The idea is to iterate from [L, R] and check if any number between the range is strong number or not.
- If yes then print the corresponding number, 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 L, int R) { for (int i = L; i <= R; i++) { if (isStrong(i)) { System.out.print(i + " "); } } } // Driver Code public static void main(String[] args) { int L=28, R = 890; // Function Call printStrongNumbers(L, R); } }
Output
145
Login/Signup to comment