-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPerfectNumberCheck.java
More file actions
32 lines (29 loc) · 1.02 KB
/
PerfectNumberCheck.java
File metadata and controls
32 lines (29 loc) · 1.02 KB
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
// 27. Write a program to check if a given number is a perfect number.
import java.util.Scanner;
public class PerfectNumberCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
boolean isPerfect = isPerfectNumber(num);
if (isPerfect) {
System.out.println(num + " is a perfect number.");
} else {
System.out.println(num + " is not a perfect number.");
}
scanner.close();
}
public static boolean isPerfectNumber(int num) {
int sum = 1; // Start with 1 (since every number is divisible by 1)
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
if (i == (num / i)) {
sum += i;
} else {
sum += (i + num / i);
}
}
}
return sum == num && num != 1;
}
}