[LeetCode] Perfect Number

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)

完美数的定义是:一个正整数,它的值等于除了它本身所有正除数之和。

所以这个和首先包含1,剩下的数由一系列正的除数与商组成。因为每一组除数和商都是成对出现的,只需要计算除数到num的开方的下取整即可。这时如果除数和商相等,只需要累加一个值即可。

class Solution {
public:
    bool checkPerfectNumber(int num) {
        int sum = 1;
        for (int i = 2; i <= sqrt(num); i++) {
            if (num % i == 0) {
                int tmp = num / i;
                sum = sum + i + (i == tmp ? 0 : tmp);
            }
        }
        return sum == num && num != 1;
    }
};
// 3 ms
原文地址:https://www.cnblogs.com/immjc/p/7659938.html