Peterson Number in Java

In this tutorial, we will learn about the Peterson number and check if the number is Peterson or not in java.

What is Peterson Number?

A number is said to be a Peterson number if the sum of factorials of each digit of the number is equal to the number itself.

Example:

Number = 145
145 = !1 + !4 + !5
= 1 + 4*3*2*1 + 5*4*3*2*1
= 1+24+120
= 145 =145

Therefore, we can see that after the sum of the factorial of 145 is equal to the number 145 itself. Hence the Peterson Number.


Java Program to check whether the number is Peterson Number or not

import java.io.*;
import java.util.*;

public class GFG
{
  // find factorial of digits
  static int[] fact = new int[]
  { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 };

  //function
  static boolean peterson(int num)
  {
    int n = num;
    int sum = 0;

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

    return (sum == n);
  }

  // main Program
  static public void main(String[] args)
  {
    int num;
    Scanner sc = new Scanner(System.in);

    System.out.print("Enter a number: ");
    num = sc.nextInt();

    if (peterson(num))
      System.out.println(num + " is a Peterson number");
    else
      System.out.println(num + " is not a Peterson number");
  }
}

Output 1:

Enter a number: 145
145 is a Peterson number

Output 2:

Enter a number: 55
55 is not a Peterson number