Table of Contents
ToggleStrong numbers are a special category of numbers in number theory where the factorials of the individual digits sum up to the original number. Though rare, these unique numbers have interesting mathematical properties.
In this post, we take a deep dive into strong number in Java. In this article we look at:
- The algorithm to check if a number is strong
- Write a complete Java program to check if number is strong or not.
- Optimise it using dynamic programming.
- Print strong numbers in a range.
So, let’s get started.
What is a Strong Number in Java with Example?
In Java, a strong number (or a digit factorial) is a number where the sum of the factorial of its individual digits equals the number itself. Mathematically, it can be represented as:
A number n is called a Strong Number if it satisfies the following condition:
- ∑ d! = n
- Where: n is the original number
- d represents each digit in n
- d! is the factorial of each digit
- ∑ is the summation symbol, representing the sum of the factorial of each digit
Examples of Strong Number
For 145:
- Digits: 1, 4, 5
- Factorial: 1! = 1, 4! = 24, 5! = 120
- Sum: 1 + 24 + 120 = 145
- Since ∑d!=145, 145 is a Strong Number.
For 216:
- Digits: 2, 1, 6
- Factorial: 2! = 2, 1! = 1, 6! = 720
- Sum: 2 + 1 + 720 = 723
- Since ∑d!=723, 216 is not a Strong Number.
To know more about Strong numbers in detail check our previous post on Strong Numbers.
Algorithm To Check Strong Number In Java
Algorithm to check if number is strong or not:
- Extract each digit of the number that needs to be checked by num%10.
- For each digit d, get the factorial of digit and add to the sum variable.
- If sum is equal to original number, then number is strong else it is not.
Program to Check Strong Number In Java
public class StrongNumber {
// Function to calculate the factorial of a number
public static int factorial(int num) {
if (num == 0 || num == 1)
return 1;
else
return num * factorial(num - 1);
}
// Function to check if a number is a strong number
public static boolean isStrongNumber(int num) {
int originalNum = num;
int sum = 0;
while (num > 0) {
int digit = num % 10;
sum += factorial(digit);
num /= 10;
}
return (sum == originalNum);
}
public static void main(String[] args) {
int num = 145; // Example number
if (isStrongNumber(num))
System.out.println(num + " is a strong number.");
else
System.out.println(num + " is not a strong number.");
}
}
Output
145 is a strong number.
Dynamic Programming Approach
The above program uses recursive way to find the factorial of number. Dynamic Programming (DP) can used to optimise the recursive approach by storing the results of subproblems (in this case, factorials of numbers) so they don’t have to be recalculated. This is particularly effective for calculating factorials because the factorial of a number builds directly on the factorial of its predecessor.
So above Factorial Function can be optimised using Dynamic Programming as:
// Factorial Function Using Dynamic Programming
public static int factorial(int num, int[] dp) {
if (num == 0 || num == 1)
return 1;
if (dp[num] != 0) // Check if factorial of num is already calculated
return dp[num];
dp[num] = num * factorial(num - 1, dp);
return dp[num];
}
In this implementation, dp
is an array that stores the factorial of each number. Before calculating the factorial of a number, we check if it’s already computed and stored in dp
.
Modified isStrongNumber
Function
public static boolean isStrongNumber(int num) {
int[] dp = new int[10]; // DP array to store factorials up to 9
int originalNum = num;
int sum = 0;
while (num > 0) {
int digit = num % 10;
sum += factorial(digit, dp);
num /= 10;
}
return (sum == originalNum);
}
Complete code to check Strong number in Java using DP looks like:
// Check Strong number in Java using DP
public class StrongNumberDP {
// Function to calculate the factorial using dynamic programming
public static int factorial(int num, int[] dp) {
// Base case: factorial of 0 or 1
if (num == 0 || num == 1)
return 1;
// If already calculated, return the stored value
if (dp[num] != 0)
return dp[num];
// Calculate factorial and store it in dp array
dp[num] = num * factorial(num - 1, dp);
return dp[num];
}
// Function to check if a number is a strong number
public static boolean isStrongNumber(int num) {
// DP array to store factorials of digits from 0 to 9
int[] dp = new int[10];
int originalNum = num;
int sum = 0;
// Extract digits and compute their factorials
while (num > 0) {
int digit = num % 10;
sum += factorial(digit, dp);
num /= 10;
}
// Compare the sum of factorials with the original number
return (sum == originalNum);
}
public static void main(String[] args) {
// Example usage
int num = 145; // Example number
if (isStrongNumber(num))
System.out.println(num + " is a strong number.");
else
System.out.println(num + " is not a strong number.");
}
}
Printing Strong Numbers Between 1 to N In Java
To print the strong numbers between 1 to N, we will loop through 1 to N and for each number we will utilise above function to check if number is Strong or not.
import java.util.Scanner;
public class StrongNumbers {
/**
* This method calculates the factorial of a given number using recursion.
*
* @param num The number for which factorial is to be computed.
* @return The factorial of the number.
*/
private static int factorial(int num) {
if (num == 0 || num == 1)
return 1; // Factorial of 0 and 1 is 1
else
return num * factorial(num - 1); // Recursive call for factorial calculation
}
/**
* This method checks if a given number is a strong number.
* A strong number is one where the sum of the factorials of its digits is equal to the number itself.
*
* @param num The number to check.
* @return true if the number is a strong number, false otherwise.
*/
private static boolean isStrongNumber(int num) {
int originalNum = num;
int sum = 0;
while (num > 0) {
int digit = num % 10; // Extract the last digit
sum += factorial(digit); // Add the factorial of the digit to the sum
num /= 10; // Remove the last digit
}
return (sum == originalNum); // Check if the sum is equal to the original number
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the upper limit N
System.out.print("Enter the value of N: ");
int N = scanner.nextInt();
// Displaying strong numbers between 1 and N
System.out.println("Strong numbers between 1 and " + N + " are:");
for (int i = 1; i <= N; i++) {
if (isStrongNumber(i)) {
System.out.print(i + " ");
}
}
scanner.close();
}
}
Output
Enter the value of N: 500
Strong numbers between 1 and 500 are:
1 2 145
Java Program to Find Strong Numbers in a Given Range l,r
To extend the code for a range (l) to (r), you just need to make slight modifications in the main()
function. Instead of asking the user for only the value of (N) and then checking from 1
to (N), you’ll prompt the user for both (l) and (r) and then check from (l) to (r).
import java.util.Scanner;
public class StrongNumbersInRange {
/**
* Calculates the factorial of a number using recursion.
*
* @param num The number for which the factorial is calculated.
* @return The factorial of the number.
*/
private static int factorial(int num) {
if (num == 0 || num == 1)
return 1; // Factorial of 0 and 1 is 1
else
return num * factorial(num - 1); // Recursive call for factorial calculation
}
/**
* Checks if a number is a strong number. A strong number is one where the sum of the factorials
* of its digits equals the number itself.
*
* @param num The number to check.
* @return true if the number is a strong number, false otherwise.
*/
private static boolean isStrongNumber(int num) {
int originalNum = num;
int sum = 0;
while (num > 0) {
int digit = num % 10; // Extracting the last digit
sum += factorial(digit); // Adding the factorial of the digit to the sum
num /= 10; // Removing the last digit
}
return (sum == originalNum); // Comparing sum with the original number
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the range start (l) and end (r)
System.out.print("Enter the range (l, r): ");
int l = scanner.nextInt();
int r = scanner.nextInt();
// Displaying strong numbers within the specified range
System.out.println("Strong numbers between " + l + " and " + r + " are:");
for (int i = l; i <= r; i++) {
if (isStrongNumber(i)) {
System.out.print(i + " ");
}
}
scanner.close();
}
}
Output
Enter the range (l, r): 100 500
Strong numbers between 100 and 500 are:
145
Note: In practice, the constant factors might be significantly larger in the brute force solution than in the DP one, especially if the range from (l) to (r) includes many numbers.
Key Takeaways
Here are the Key takeaways on Strong Numbers in Java:
- A number is strong if the sum of the factorials of its digits equals itself (e.g. 145)
- We can check if a number is strong in Java by extracting digits, computing factorials, and comparing the sum to the original.
- Dynamic programming efficiently precomputes and stores factorial results, speeding up strong number calculations.
- Printing strong numbers involves looping from 1 to N and checking each number if it is strong.
Checkout more Java Tutorials here.
Similar Posts
Add Days To The Current Date in Java
Calculate Area of Hexagon in Java
Program to Calculate EMI in Java
Calculate Area of a Circle in Java
I hope You liked the post 👍. For more such posts, 📫 subscribe to our newsletter. Try out our free resume checker service where our Industry Experts will help you by providing resume score based on the key criteria that recruiters and hiring managers are looking for.
FAQ
Can any number be a strong number?
Answer: No, not every number is a strong number. Strong numbers are relatively rare and specific. Most numbers do not satisfy the condition of having the sum of their digit factorials equal to themselves.
How do you calculate the factorial of a number?
Answer: To calculate the factorial of a non-negative integer n, you multiply all positive integers from 1 to n together. For example, 5! (read as “5 factorial”) is equal to 5 x 4 x 3 x 2 x 1, which equals 120.
Are there any well-known strong numbers other than 145?
Answer: Yes, 145 is the most well-known strong number. However, there are other strong numbers, such as 40,585 which is the second smallest strong number. Strong numbers are relatively rare, and there are only a few known examples.
How can I find strong numbers?
Answer: Finding strong numbers typically involves writing a program or using a computer algorithm to check numbers one by one. There is no known efficient formula for generating strong numbers, so it often involves a brute-force search.