Peterson Number in Java

A Peterson Number is a number in which the sum of the factorials of its digits is equal to the original number.

Peterson Number in Java

A Peterson Number is a special number where the sum of the factorials of its digits is exactly equal to the number itself.

Example:
145 → 1! + 4! + 5! = 1 + 24 + 120 = 145
So, 145 is a Peterson Number.

Java Program:


public class PetersonNumber {

    // Function to calculate factorial of a digit
    static int factorial(int n) {
        int fact = 1;
        for (int i = 1; i <= n; i++) {
            fact *= i;
        }
        return fact;
    }

    // Function to check if a number is a Peterson Number
    static boolean isPeterson(int num) {
        int temp = num;
        int sum = 0;

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

        return sum == num;
    }

    public static void main(String[] args) {
        int num = 145;

        if (isPeterson(num)) {
            System.out.println(num + " is a Peterson Number");
        } else {
            System.out.println(num + " is NOT a Peterson Number");
        }
    }
}

Practice Challenges

  1. Modify the program to print all Peterson Numbers between 1 and 1000.
  2. Take a number from user input and check if it's a Peterson Number.
  3. Optimize the program by precomputing factorials of digits 0–9.