问题描述:

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)

class Solution {
public:
    bool checkPerfectNumber(int num) {
     }
};

题目翻译:

首先给出perfect number的定义,其指的是所有能够整除这个数的除数之和等于这个数,注意除数不包括此数本身。

现给定一个整数n,编写一个函数,使其返回这个整数n是否为perfect number。

比如:

输入: 28
输出: True
解释: 28 = 1 + 2 + 4 + 7 + 14

注意:输入的参数n不会超过100,000,000.

解题思路:

由于除数需要一一列举,所以需要循环列举,循环的停止条件即为除数和商相等或者之后的除数为上次的商。

class Solution {
public:
    bool checkPerfectNumber(int num) {
        int temp = 1;
        int sum = 1;
        if(num == 0 || num == 1) return false;
        int i = 2;
        while(num % i < num)
        {
            if(num % i == 0)
            {
                if(num/i == i)
                {
                    sum += i + i;
                    break;
                }
                else if(num / i != temp)
                {
                    sum += num/i + i;
                    temp = i;
                }
                else break;
                i++;
            }  
            else if(num % i != 0) i++;
        }
        if(sum == num) return true;
        else return false;
    }
};