Exploring Strong Numbers in Java: A Code Explanation

Yogi Siddeswara 0

What Are Strong Numbers?

Before we delve into the code, let's understand what strong numbers are. A strong number (or factorial number) is a number that equals the sum of its individual digits' factorials.

For example, let's take the number 145:

- 1! + 4! + 5! = 1 + 24 + 120 = 145

Now, let's explore how to determine if a number is strong using Java.


The Java Code Explanation

package in.studyecart.impprograms;

import java.util.Scanner;

public class SECJAP112 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a Number:");
        int actual_num = input.nextInt(), num = actual_num, fact_sum = 0;

        while (actual_num != 0) {
            int digit = actual_num % 10;
            fact_sum = fact_sum + getFactorial(digit);
            actual_num = actual_num / 10;
        }

        if (fact_sum == num) {
            System.out.println("Given number is a Strong Number!!");
        } else {
            System.out.println("Given number is Not a Strong Number!!");
        }
    }

    // Logic for factorial
    static int getFactorial(int n) {
        int fact = 1;
        if (n == 0 || n == 1) {
            return 1;
        } else {
            for (int i = n; i > 1; i--) {
                fact = fact * i;
            }
            return fact;
        }
    }
}





(code-box)


How the Code Works

1. We begin by taking input from the user, which is the number we want to check for being a strong number.

2. Using a while loop, we break down the number into its individual digits, calculate the factorial of each digit, and sum them up.

3. Finally, we compare the sum of factorials with the original number. If they match, we conclude that the number is a strong number; otherwise, it is not.


Understanding strong numbers and how to identify them with this Java program can be a valuable addition to your programming knowledge. Feel free to try this code with different numbers and explore the fascinating world of factorials and strong numbers in Java programming. Happy coding!


Boost your Java programming skills with these top 10 beginner-friendly Java programs! Check them out clickhere.

🚀 Elevate Your Career with Studyecart! 📚📊

🔥 Get instant job notifications and ace interviews with Studyecart. 📌

click here to get app  #StudyecartApp #CareerBoost

Post a Comment

0 Comments