TeachingBee

Strong Number In Java Program

Strong Number In Java Program TeachingBee

Strong 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:

  1. Extract each digit of the number that needs to be checked by num%10.
  2. For each digit d, get the factorial of digit and add to the sum variable.
  3. 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

Strong Numbers.

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

Leap Year Program 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?

How do you calculate the factorial of a number?

Are there any well-known strong numbers other than 145?

How can I find strong numbers?

90% of Tech Recruiters Judge This In Seconds! 👩‍💻🔍

Don’t let your resume be the weak link. Discover how to make a strong first impression with our free technical resume review!

Related Articles

ascii value in java

Print ASCII Value in Java

In this article we will into the ASCII table in C, exploring its various character sets—from control characters to printable characters, including letters, digits, and special symbols—and demonstrates how to

data hiding in java

Data Hiding In Java

In this article we will discuss data hiding in Java which is an important concept in object-oriented programming. We will cover So let’s get started. What is Data Hiding in

Why Aren’t You Getting Interview Calls? 📞❌

It might just be your resume. Let us pinpoint the problem for free and supercharge your job search. 

Newsletter

Don’t miss out! Subscribe now

Log In