Java Program to Check Peterson Number
A Peterson number is a number that equals the sum of the factorials of its digits. It is also known as a strong number or a Krishnamurthy number.
145 is a Peterson number because:
1! + 4! + 5! = 1 + 24 + 120 = 145
Only four Peterson numbers exist in base 10: 1, 2, 145 and 40585.
1. Check a Peterson Number with User Input
The program splits the number into digits with % 10 and / 10, adds the factorial of each digit, and compares the total with the original number.
import java.util.Scanner;
public class PetersonNumber {
static int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
static boolean isPeterson(int number) {
int sum = 0;
for (int temp = number; temp > 0; temp /= 10) {
sum += factorial(temp % 10);
}
return sum == number;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
scanner.close();
System.out.println(number + (isPeterson(number) ? " is a Peterson number." : " is not a Peterson number."));
}
}
Output 1
Enter a number: 145 145 is a Peterson number.
Output 2
Enter a number: 234 234 is not a Peterson number.
For 234: 2! + 3! + 4! = 2 + 6 + 24 = 32, which is not 234.
2. Faster Check Using Precomputed Factorials
A digit is always 0 to 9, so the ten factorials can be stored in an array once instead of being recalculated for every digit. This version prints all Peterson numbers up to 100,000.
public class PetersonRange {
// FACT[d] holds d! for every digit d
static final int[] FACT = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
static boolean isPeterson(int number) {
int sum = 0;
for (int temp = number; temp > 0; temp /= 10) {
sum += FACT[temp % 10];
}
return sum == number;
}
public static void main(String[] args) {
System.out.println("Peterson numbers from 1 to 100000:");
for (int n = 1; n <= 100_000; n++) {
if (isPeterson(n)) {
System.out.print(n + " ");
}
}
System.out.println();
}
}
Output
Peterson numbers from 1 to 100000: 1 2 145 40585
3. Summary
- A Peterson (strong) number equals the sum of the factorials of its digits, such as 145 = 1! + 4! + 5!.
- Split the number into digits with
% 10and/ 10. - Store the factorials of 0 to 9 in an array to avoid recalculating them.
- The only Peterson numbers are 1, 2, 145 and 40585.
Related Programs
Was this tutorial helpful?