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));

Reference


xufeng
8 声望3 粉丝

有多少人工就有多少智能