Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Method 1: Using Simple Iteration
2.1.
Java
3.
Method 2: Using Recursive Function
3.1.
Java
4.
Method 3: Smart Dynamic Programming Approach
4.1.
Java
5.
Frequently Asked Questions
5.1.
What is a strong number?
5.2.
Why use dynamic programming to calculate strong numbers?
5.3.
Can any number be a strong number?
6.
Conclusion
Last Updated: Apr 30, 2024
Easy

Strong Number in Java

Author Rinki Deka
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

In mathematics, a strong number is a special type of number with unique properties. It is defined as a positive integer that is greater than the sum of all the smaller positive divisors of that number. Strong numbers have interesting characteristics & play a role in various mathematical concepts. 

Strong Number in Java

In this article, we will learn what strong numbers are, how to identify them, & different methods to find strong numbers in Java programming language.

Method 1: Using Simple Iteration

To determine if a number is a strong number in Java, one straightforward approach is through simple iteration. This method involves breaking down the number into its individual digits, computing the factorial of each digit, and then summing these factorials. If the sum equals the original number, then it's a strong number.

Here's a step-by-step breakdown of how to implement this method in Java:

  • Extract Digits: Start by extracting each digit from the number. This can be done using a while loop that continues as long as the number is greater than zero. Use the modulus operator (%) to get the last digit of the number, and then reduce the number by dividing it by 10.
     
  • Compute Factorials: For each digit obtained, calculate its factorial. You can write a separate method that takes a digit as input and returns the factorial using a for loop.
     
  • Sum the Factorials: As you calculate each digit's factorial, add it to a sum variable. Initialize this sum at zero before the loop starts.
     
  • Check the Condition: After the loop ends, compare the sum of the factorials with the original number. If they are equal, the number is a strong number.
     

Here’s the Java code that implements the above steps:

  • Java

Java

public class StrongNumberChecker {
public static void main(String[] args) {
int number = 145; // Example number
if (isStrongNumber(number)) {
System.out.println(number + " is a strong number.");
} else {
System.out.println(number + " is not a strong number.");
}
}

public static boolean isStrongNumber(int number) {
int originalNumber = number;
int sum = 0;

while (number > 0) {
int digit = number % 10;
sum += factorial(digit);
number /= 10;
}

return sum == originalNumber;
}

public static int factorial(int digit) {
int fact = 1;
for (int i = 1; i <= digit; i++) {
fact *= i;
}
return fact;
}
}

Output

145 is a strong number.


This code defines a class StrongNumberChecker that includes a method isStrongNumber to determine if a given number is strong. It also includes a helper method factorial to compute the factorial of a digit. The program is straightforward, using basic loops & arithmetic operations, making it easy to understand & implement even for beginners.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Method 2: Using Recursive Function

Recursive functions are powerful in breaking down complex problems into simpler, manageable parts. In the context of identifying strong numbers, a recursive function can efficiently calculate factorials, which are central to this method. This approach not only simplifies the code but also enhances its readability.

Here’s how you can use recursion to check for strong numbers in Java:

  • Recursive Factorial Calculation: Define a recursive method that calculates the factorial of a number. In recursion, the function calls itself with a decremented value until it reaches the base case, which is when the number is either 0 or 1.
     
  • Extract and Sum Factorials: Similar to the iterative method, extract each digit from the number using a loop, and for each digit, use the recursive factorial function to calculate the factorial. Sum these factorials as you go.
     
  • Compare Sum with Original Number: After calculating the total sum of the factorials of all digits, compare this sum to the original number. If they match, the number is a strong number.


Here’s the Java code illustrating this method:

  • Java

Java

public class StrongNumberRecursive {
public static void main(String[] args) {
int number = 145; // Example number
if (isStrongNumber(number)) {
System.out.println(number + " is a strong number.");
} else {
System.out.println(number + " is not a strong number.");
}
}

public static boolean isStrongNumber(int number) {
int originalNumber = number;
int sum = 0;

while (number > 0) {
int digit = number % 10;
sum += factorial(digit);
number /= 10;
}

return sum == originalNumber;
}

public static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}
}

Output

145 is a strong number.


In this code, the factorial method is recursive. It multiplies the number n by the factorial of n-1, reducing n each time until it reaches the base cases (0 or 1). This recursive approach not only computes the factorials needed to check if a number is strong but does so with less code compared to non-recursive methods.

This method is particularly useful for those who are learning how to employ recursion in practical programming scenarios. The recursive calculation of factorial is a common example in many programming courses, making this approach familiar & accessible to students.

Method 3: Smart Dynamic Programming Approach


Dynamic programming is an optimization strategy that solves problems by breaking them down into simpler subproblems and storing the results of these subproblems to avoid computing the same results multiple times. This method is particularly effective for calculating factorials when determining strong numbers, as it can significantly speed up the process by reusing previously computed results.

Here's how dynamic programming can be applied to the problem of identifying strong numbers in Java:

  • Precompute Factorials: Create an array to store the factorials of numbers from 0 to 9. This step is done once and allows quick access to any small factorial needed without recalculating it repeatedly.
     
  • Extract Digits & Use Precomputed Factorials: Like the previous methods, extract each digit of the number. Instead of computing the factorial each time, simply retrieve the precomputed factorial from the array.
     
  • Sum the Factorials: Sum the factorials of the digits as you extract them from the number.
     
  • Compare the Sum with the Original Number: If the sum of the factorials equals the original number, then the number is a strong number.
     

Here is the Java code that uses dynamic programming for checking strong numbers:

  • Java

Java

public class StrongNumberDynamic {
private static int[] factorial = new int[10];

static {
// Precomputing factorials of digits from 0 to 9
factorial[0] = 1;
for (int i = 1; i < factorial.length; i++) {
factorial[i] = factorial[i - 1] * i;
}
}

public static void main(String[] args) {
int number = 145; // Example number
if (isStrongNumber(number)) {
System.out.println(number + " is a strong number.");
} else {
System.out.println(number + " is not a strong number.");
}
}

public static boolean isStrongNumber(int number) {
int originalNumber = number;
int sum = 0;

while (number > 0) {
int digit = number % 10;
sum += factorial[digit];
number /= 10;
}

return sum == originalNumber;
}
}

Output

145 is a strong number.


In this implementation, the factorial array holds the factorials of the digits from 0 to 9, computed once during the static initialization block. When checking if a number is strong, the program retrieves the factorial of each digit from this array, which makes the process faster and more efficient, especially for numbers with many digits.

This dynamic programming approach is ideal for problems where calculations are repeated, as it reduces the time complexity by avoiding redundant operations and leverages previously computed results.

Frequently Asked Questions

What is a strong number?

A strong number is one where the sum of the factorials of its digits equals the number itself. For example, 145 is a strong number because 1! + 4! + 5! = 145.

Why use dynamic programming to calculate strong numbers?

Dynamic programming reduces computation time by storing results of subproblems like factorial calculations. This avoids redundant operations, making the process faster, especially for larger numbers.

Can any number be a strong number?

No, not all numbers can be strong numbers. Only specific numbers meet the criteria, making strong numbers rare and interesting to study.

Conclusion

In this article, we have talked about three methods to determine if a number is a strong number in Java. Starting with simple iteration, we moved to a recursive function approach, and finally applied a smart dynamic programming technique to make the process efficient. Each method provides a unique way to tackle the problem, giving programmers multiple tools for their coding arsenal. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Process vs Thread in Java
Next article
Nested Class in Java
Live masterclass