-
Notifications
You must be signed in to change notification settings - Fork 0
/
Peterson_Number.java
45 lines (40 loc) · 1.73 KB
/
Peterson_Number.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// In this section, we will learn what is Peterson number and how can we check
// whether a given number is Peterson or not through a Java program.
// Peterson Number
// A number is said to be Peterson if the sum of factorials of each digit is
// equal to the sum of the number itself.
import java.io.*;
import java.util.*;
class Peterson_Number {
// an array is defined for the quickly find the factorial
static int[] factorial = new int[] { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600 };
// driver code
public static void main(String args[]) {
// constructor of the Scanner class
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number to check: ");
// reading a number from the user
int n = sc.nextInt();
// calling the user-defined function to check Peterson number
if (isPeterson(n))
System.out.println("The given number is a Peterson number.");
else
System.out.println("The given number is not a Peterson number.");
}
// function to check the given number is Peterson or not
static boolean isPeterson(int n) {
int num = n;
int sum = 0;
// loop executes until the condition becomes false
while (n > 0) {
// determines the last digit of the given number
int digit = n % 10;
// determines the factorial of the digit and add it to the variable sum
sum += factorial[digit];
// removes the last digit of the given number
n = n / 10;
}
// compares sum with num if they are equal returns the number itself
return (sum == num);
}
}