Description
We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.
Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not.
Example:
Input: 28
Output: True
Explanation: 28 = 1 + 2 + 4 + 7 + 14
Note: The input number n will not exceed 100,000,000. (1e8)
My solution
最初暴力方式:TLE
class Solution {
public:
bool checkPerfectNumber(int num) {
int sum = 0;
for (int i = 1; i < num; ++i) if (num % i == 0) sum += i;
return sum == num;
}
};
参照Discuss后的修正方式
这里的修正就是把每次+i
改为+i+num/i
, 也就是从两头同时加起来, 因为每次得到的divisor是成对的 !
class Solution {
public:
bool checkPerfectNumber(int num) {
if (num == 1) return false;
int sum = 1;
for (int i = 2; i < sqrt(num); ++i) if (num % i == 0) sum += i + num / i;
return sum == num;
}
};
Discuss | TRIIIIIIIIIIICK !!!
class Solution {
public:
bool checkPerfectNumber(int num) {
static unordered_set<int> n = {6, 28, 496, 8128, 33550336};
return n.count(num);
}
};
OR :
I did it the "hard" way in BASIC 40 years ago, but I knew there aren't many perfect numbers, so rather than risk not doing it efficiently enough not to time out, I did it similarly.
return ((num == 6) || (num == 28) || (num == 496) || (num == 8128) || (num == 33550336));
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。