-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
36 lines (32 loc) · 863 Bytes
/
Main.java
File metadata and controls
36 lines (32 loc) · 863 Bytes
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
/**
* 找出前五个完美数
* 完美数是指一个数恰好等于它的因子之和
* 例如:6 = 1 + 2 + 3
* @Author: FoskyM
* @Date: 2023/10/16 22:16
*/
package Work3;
public class Main {
public static void main(String[] args) {
int count = 0;
for (int p = 1; count < 5; p++) {
// 2 ^ (p - 1) * (2 ^ p - 1)
int num = (1 << (p - 1)) * ((1 << p) - 1);
if (isPerfectNumber(num)) {
count++;
System.out.println(num);
}
}
}
static boolean isPerfectNumber(int n) {
if (n < 2) return false;
int sum = 1;
for (int i = 2; i <= (int)Math.sqrt(n); i++) {
if (n % i == 0) {
sum += i + n / i;
if (sum > n) return false;
}
}
return n == sum;
}
}