Google News
logo
Java program to Peterson Number
A Peterson number is a number that is equal to the sum of factorials of its digits in a given base.

For example, 145 is a Peterson number as 1! + 4! + 5! = 1 + 24 + 120 = 145. Here's a Java program to check if a number is a Peterson number or not :
Program :
import java.util.Scanner;

public class PetersonNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = sc.nextInt();
        int temp = n, sum = 0;
        while (temp > 0) {
            int digit = temp % 10;
            sum += factorial(digit);
            temp /= 10;
        }
        if (sum == n) {
            System.out.println(n + " is a Peterson number.");
        } else {
            System.out.println(n + " is not a Peterson number.");
        }
    }

    public static int factorial(int n) {
        int fact = 1;
        for (int i = 2; i <= n; i++) {
            fact *= i;
        }
        return fact;
    }
}
Output :
Enter a number: 145
145 is a Peterson number.
Enter a number: 123
123 is not a Peterson number.
* In this program, we first take an input number from the user using the Scanner class.

* We then find the sum of factorials of its digits by dividing the number by 10 repeatedly and finding the factorial of the remainder.

* We then compare this sum with the original number to check if it's a Peterson number or not. The factorial() method is used to find the factorial of a given number.