forked from raman1200/community_issues
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Peterson Number in Java
39 lines (33 loc) · 1019 Bytes
/
Peterson Number in 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
import java.util.Scanner;
public class PetersonNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
scanner.close();
if (isPetersonNumber(number)) {
System.out.println(number + " is a Peterson number.");
} else {
System.out.println(number + " is not a Peterson number.");
}
}
public static boolean isPetersonNumber(int number) {
int originalNumber = number;
int numDigits = countDigits(number);
int sum = 0;
while (number > 0) {
int digit = number % 10;
sum += Math.pow(digit, numDigits);
number /= 10;
}
return sum == originalNumber;
}
public static int countDigits(int number) {
int count = 0;
while (number > 0) {
count++;
number /= 10;
}
return count;
}
}