int sum = 1; for (int d = 2; d * d <= num; ++d) { if (num % d == 0) { sum += d; if (d * d < num) { sum += num / d; } } } return sum == num; } }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
funccheckPerfectNumber(num int)bool { if num == 1 { returnfalse }
sum := 1 for d := 2; d*d <= num; d++ { if num%d == 0 { sum += d if d*d < num { sum += num / d } } } return sum == num }
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
boolcheckPerfectNumber(int num){ if (num == 1) { returnfalse; }
int sum = 1; for (int d = 2; d * d <= num; ++d) { if (num % d == 0) { sum += d; if (d * d < num) { sum += num / d; } } } return sum == num; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
var checkPerfectNumber = function(num) { if (num === 1) { returnfalse; }
let sum = 1; for (let d = 2; d * d <= num; ++d) { if (num % d === 0) { sum += d; if (d * d < num) { sum += Math.floor(num / d); } } } return sum === num; };
复杂度分析
时间复杂度:O(\sqrt\textit{num})。
空间复杂度:O(1)。
方法二:数学
根据欧几里得-欧拉定理,每个偶完全数都可以写成
2^{p-1}(2^p-1)
的形式,其中 p 为素数且 2^p-1 为素数。
由于目前奇完全数还未被发现,因此题目范围 [1,10^8] 内的完全数都可以写成上述形式。
这一共有如下 5 个:
6, 28, 496, 8128, 33550336
[sol2-Python3]
1 2 3
classSolution: defcheckPerfectNumber(self, num: int) -> bool: return num == 6or num == 28or num == 496or num == 8128or num == 33550336
[sol2-C++]
1 2 3 4 5 6
classSolution { public: boolcheckPerfectNumber(int num){ return num == 6 || num == 28 || num == 496 || num == 8128 || num == 33550336; } };
[sol2-Java]
1 2 3 4 5
classSolution { publicbooleancheckPerfectNumber(int num) { return num == 6 || num == 28 || num == 496 || num == 8128 || num == 33550336; } }
[sol2-C#]
1 2 3 4 5
publicclassSolution { publicboolCheckPerfectNumber(int num) { return num == 6 || num == 28 || num == 496 || num == 8128 || num == 33550336; } }
[sol2-Golang]
1 2 3
funccheckPerfectNumber(num int)bool { return num == 6 || num == 28 || num == 496 || num == 8128 || num == 33550336 }
[sol2-C]
1 2 3
boolcheckPerfectNumber(int num){ return num == 6 || num == 28 || num == 496 || num == 8128 || num == 33550336; }
[sol2-JavaScript]
1 2 3
var checkPerfectNumber = function(num) { return num === 6 || num === 28 || num === 496 || num === 8128 || num === 33550336; };