Strong number program in Java
In this post, you will learn how to write a strong number program using the Java programming language.
Factorial, in mathematics, the product of all positive integers less than or equal to a given positive integer and denoted by that integer and an exclamation point. The factorial of a number n is denoted by n!. This is the product of all positive numbers less than or equal to n. It is calculated as —
n! = n X (n-1) X (n-3) X ……… X 3 X 2 X 1
The factorial operation generally comes across many mathematical operations, like- combinatorics, algebra, analysis.
A strong number is a number in which the sum of the factorial of the digits is equal to the number itself. Like- 1, 2, 145, 40585, and so on. Example-
Input Number - 145 Sum of Factorial of the digits - 1! + 4! + 5! 1 + 24 + 120 145 // Strong Number
As you can see above, the input number is equal to the sum of the factorial of the digits. So, the number 145 is the factorial number. Again, let’s check for the other number.
Input Number - 162 Sum of Factorial of the digits - 1! + 6! + 2! 1 + 720 + 2 723 // Not a Strong Number
Java Strong Number Program Source Code
Here is the program to check whether the input number is a strong number or not in Java.
In the given example, we have created an instance of the scanner class and declared variables to store the number, the sum of factorial of digits and a temp variable. Then, we ask the user to provide the number. The while loop calculates the sum of the factorial of digits.
Inside the while loop, the factorial of the last digit is calculated and added to the sum. In each iteration, the ‘fact‘ variable is initialised to 1, as for every digit we have its own factorial, and the variable temp is divided by 10, so that we can get the last digit and then the second last digit, and so on. At last, we have checked if the computed sum is equal to the original number. If so, then the given number is a strong number, otherwise not.
import java.util.Scanner; public class SpecialNumberProgram < public static void main(String args[]) < int temp, input_num, last_digit, sum_of_fact = 0; Scanner sc = new Scanner(System.in); System.out.print("Please enter a number: "); //reads an integer input from the user input_num = sc.nextInt(); temp = input_num; while (temp >0) < //finds the last digit last_digit = temp % 10; //variable to store the factorial int fact=1; //calculates factoria for(int i=1; i//calculates the sum of all factorials sum_of_fact = sum_of_fact + fact; temp = temp / 10; > //compares the sum with the given number if(input_num ==sum_of_fact) < System.out.println(input_num+ " is a strong number."); >else < System.out.println(input_num+ " is not a strong number."); >> >
Please enter a number: 145 145 is a special number.
Strong program in java
This program checks if a given number is a strong number or not. A strong number is a number whose sum of factorials of each digit is equal to the original number.
- The program first prompts the user to enter a number. It then takes the input and saves it in the variable num . The variable originalNum is used to store the original value of num for later comparison.
- Next, the program enters a while loop that runs until num is greater than 0. Within the loop, the variable rem is used to store the remainder of num divided by 10 (i.e., the last digit of num ).
- Then, a for loop is used to calculate the factorial of rem , which is stored in the variable fact . The factorial is calculated by starting with i as 1 and multiplying fact by i in each iteration until i reaches rem . The result is then added to the variable sum .
- After the for loop finishes, num is divided by 10, which drops the last digit, and the loop continues with the next digit. This process continues until all digits have been processed.
- Finally, the program checks if sum is equal to originalNum . If they are equal, the program prints that the original number is a strong number. Otherwise, it prints that the original number is not a strong number.
Note that this program assumes that the input is a positive integer. If the input is not a positive integer, the program behavior is undefined.
Source Code
import java.util.Scanner; public class strong { //Write a program to check the given number is Strong number or not. public static void main(String args[]) { int num,originalNum,rem,fact,i,sum=0; Scanner in = new Scanner(System.in); System.out.println("Enter a number : "); num=in.nextInt(); originalNum=num; while (num>0)//145>0 14>0 1>0 { rem=num%10; //System.out.println("Reminder : "+rem); fact=1; for(i=1;irem;i++){ fact*=i;//fact=fact*i } //System.out.println("fact : "+fact); sum+=fact; num=num/10; } if (sum == originalNum) { System.out.println(originalNum + " is STRONG NUMBER"); } else { System.out.println(originalNum + " is not a STRONG NUMBER"); } } }
Output
Enter a number : 145 145 is STRONG NUMBER
Enter a number : 234 234 is not a STRONG NUMBER
Basic Programs
- Java Introduction
- History of Java
- Installation
- Basic Program in Java
- Command Line Arguments in Java
- Single and Multi Line Comments in Java
- Variables in Java
- Type Casting in Java
- Arithmetic Operators in Java
- Arithmetic Assignment operators in Java
- Relational Operators in Java
- Logical Operators in Java
- Conditional or Ternary Operators in Java
- Unary Operators in Java
- Bitwise & Shift Operators in Java
- Scanner Class in Java
- IF Statement in Java
- IF ELSE Statement in Java
- ELSE IF Ladder in Java
- Nested If in Java
- Switch Statement in Java
- Group Switch Statement in Java
- While Loop in Java
- do While Loop in Java
- For Loop in Java
- Enhanced for loop in Java
- Nested For Loop in Java
- Break & Continue in Java
- Factorial in Java
- Sum and Average of N Numbers in Java
- Fibonacci Series in Java
- Reverse of n digit number in Java
- Number is Palindrome or Not in Java
- Armstrong Number in Java
- Armstrong Number between 100-999 in Java
- Multiplication tables in Java
- Factor of the given number in Java
- Number is prime or not in Java
- Prime Number between 100-999 in Java
- Perfect Number in Java
- Strong Number in Java
- Array in Java
- Count odd or even numbers in Java
- Ascending Order in Java
- Insert an element (specific position) into an array in Java
- Find the duplicate values of an array in Java
- Two Dimension Arrays in Java
- Jagged-Array in Java
- Jagged-Array Using For Each Loop in Java
- ASCII in Java
- String in Java
- StringBuffer & StringBuilder in Java
- count Vowels,Capital letters,small letters,numbers and space in Java
- Reverse A String in Java
- convert the given string into UPPERCASE in Java
- convert the given string into lowercase in Java
- convert the given string into Capitalized Each Word in Java
- convert the given string into tOGGLE cASE wORD in Java
- Math Functions in Java
- Types of Methods in Java
- Returning Arrays from Method in Java
- Static Member Function in Java
- Convert Decimal To Binary in Java
- Introduction of Object Oriented Programming in Java
- Class & object in Java
- Data Hiding Getter & Setter in Java
- Constructor in Java
- Parametrized Constructor & Constructor Overloading in Java
- Copy Constructor in Java
- Arrays of Objects in Java
- Nesting of Methods in Java
- Single Inheritance in Java
- Multilevel Inheritance in Java
- Hierarchical Inheritance in Java
- Method With varargs in Java
- Method Overloading in Java
- Method Overriding in Java
- Abstract Class in Java
- Smart Phone Example using Abstract Class in Java
- What is interface in Java
- Implement multiple interfaces in Java
- More About Interface in Java
- Difference Between Abstract Class and Interface in Java
- Nested Inner Class in Java
- Local Inner Class in Java
- Anonymous Inner Class in Java
- Static Inner Class in Java
- Static Members in Java
- Static Blocks in Java
- Final in Java
- Final Methods in Java
- Final Class in Java
- Singleton Class in Java
- Enumeration in Java
- Date and Time Functions in Java
- Wrapper Class — Converting primitive number to number object in Java
- Wrapper Class — Converting number object to primitive number in Java
- Wrapper Class — Converting primitive number to string object in Java
- Wrapper Class — Converting string object to primitive numbers in Java
- Wrapper Class — Converting numeric string object to primitive numbers in Java
- Shallow Copy Object Cloning in Java
- Deep Copy Object Cloning in Java
- Java Reflection API in Java
- Calling Private Method in Java Class using Reflection API in Java
Strong Number Program in Java
If the sum of the factorial of individual digits of a number is equal to the same number then the number is called a strong number. In this post, we will develop a strong number program in Java.
Example:-
145 = 1! + 4! + 5! = 1 + 24 + 120 = 145
So, 145 is a strong number.
234 = 2! + 3! + 4! = 2 + 6 + 24 = 32
So, 234 is not a strong number.
40585 = 4! + 0! + 5! + 8! + 5! = 24 + 1 + 120 + 40320 + 120 = 40585
So, 40585 is a strong number.
Procedure to develop a method to check number is a strong number or not
1) Take a number as input
2) Take a sum variable and initialize it with 0
3) Find the last digit of the number
4) Calculate factorial of that last digit
5) Add factorial result in the sum
6) remove the last digit from the number
7) Repeat steps 3 to 6 until the number becomes 0.
8) If the sum is equal to the input (number) then it is a strong number
The Java method to check the number is a strong number or not, can be written as below:-
public static boolean isStrong(int number) < // declare variables int sum = 0, lastDigit = 0; //store number in a temporary variable int tempNum = number; // traverse through all digits of number while(tempNum != 0) < // find last digit lastDigit = tempNum % 10; // calculate factorial and // add it to the sum sum += factorial(lastDigit); // remove last digit tempNum /= 10; >// compare sum and number if(sum == number) return true; // strong number return false; // not a strong number >
We are storing the actual number in a temporary variable because at last, we need to compare the result (sum) with the actual number. If the result(sum) is equal to the actual number then the number is a strong number else it is not a strong number.
Java program to check strong number
Now based on the above method we will develop a strong number program in the Java programming language. We will develop isStrong(-) method to check the number is a strong number or not and the factorial(-) method to find the factorial of a number.
import java.util.Scanner; public class StrongNumber < // Checks the number is strong number or not public static boolean isStrong(int number) < // declare variables int sum = 0, lastDigit = 0; int tempNum = number; // traverse through all digits of number while(tempNum != 0) < lastDigit = tempNum % 10; sum += factorial(lastDigit); tempNum /= 10; >// compare sum and number if(sum == number) return true; return false; > // calculate factorial of an integer public static long factorial(int n) < long fact = 1; for(int i=1; ireturn fact; > public static void main(String[] args) < // declare variables int number = 0; boolean result = false; //create Scanner class object to take input Scanner scan = new Scanner(System.in); // take input from end-user System.out.print("Enter an integer number:: "); number = scan.nextInt(); // check number is strong number or not result = isStrong(number); if(result) System.out.println(number + " is a strong number."); else System.out.println(number + " is not a strong number"); // close Scanner class object scan.close(); >>
The output for different test-cases:-
Enter an integer number:: 145
145 is a strong number.
Enter an integer number:: 146
146 is not a strong number
Optimization
We can analyze that the last digit will be always from 0 to 9, and every time we need to find the factorial from 0 to 9 only. So, it is a better idea to calculate the factorial value from 0 to 9 and store it in an array. For the large numbers, It will be an optimized solution for checking the number is a strong number or not. Conclusion:- before checking the number is a strong number or not, calculate factorial from 0 to 9 and store it in an array. It can be done as below:-
// Array to store factorial value // from 0 to 9 static int fact[] = new int[10]; // static block to calculate factorial static < // factorial of 0 and 1 is 1 fact[0] = fact[1] = 1; // factorial is also calculated as // n! = (n-1)! * n for(int i=2; i
The static block executes before executing the main method so, the factorial values from 0 to 9 will be calculated and stored in the array fact[]. Now, inside the isStrong() method for the factorial value use this array as,
// add factorial value of last digit // to the sum variable sum += fact[lastDigit];
In the below Java program, we used this optimized solution to check the number is a strong number or not.
Optimized program to check number is Strong number or not
import java.util.Scanner; public class StrongNumber < // Array to store factorial value // from 0 to 9 static int fact[] = new int[10]; // static block to calculate factorial static < fact[0] = fact[1] = 1; for(int i=2; i// Checks the number is strong number or not public static boolean isStrong(int number) < // declare variables int sum = 0, lastDigit = 0; int tempNum = number; // traverse through all digits of number while(tempNum != 0) < lastDigit = tempNum % 10; sum += fact[lastDigit]; tempNum /= 10; >// compare sum and number return (sum == number); > // main method public static void main(String[] args) < // declare variables int number = 0; boolean result = false; //create Scanner class object and take input Scanner scan = new Scanner(System.in); System.out.print("Enter an integer number:: "); number = scan.nextInt(); // check number is strong number or not result = isStrong(number); if(result) System.out.println(number + " is a strong number."); else System.out.println(number + " is not a strong number"); // close Scanner class object scan.close(); >>
Find strong number in Java within a given range
We can also find all the strong numbers in Java within a given range. For this purpose, we need to take the help of loops. We will take range values as minRange and maxRange . Later we will find all strong number which belongs to this range.
import java.util.Scanner; public class StorngNumberInRange < // Array to store factorial value // from 0 to 9 static int fact[] = new int[10]; // static block to calculate factorial static < fact[0] = fact[1] = 1; for(int i=2; i> // Checks the number is strong number or not public static boolean isStrong(int number) < // declare variables int sum = 0, lastDigit = 0; int tempNum = number; // traverse through all digits of number while(tempNum != 0) < lastDigit = tempNum % 10; sum += fact[lastDigit]; tempNum /= 10; >// compare sum and number return (sum == number); > public static void main(String[] args) < // declare variables int minRange = 0, maxRange = 0; //create Scanner class object to take input Scanner scan = new Scanner(System.in); System.out.print("Enter the minimum value of range:: "); minRange = scan.nextInt(); System.out.print("Enter the maximum value of range:: "); maxRange = scan.nextInt(); // loop System.out.println("The Strong number from "+ minRange + " to "+ maxRange+" are: "); for(int i=minRange; i// close Scanner class object scan.close(); > >
Enter the minimum value of range:: 1
Enter the maximum value of range:: 1000000
The Strong number from 1 to 1000000 are:
1 2 145 40585
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!