【leetcode】507.Perfect Number

题目如下:

解题思路:因为n的最大值是1e8,所以暴力计算是不行的。首先,我们可以排除掉素数,因为素数的整数因子只有1和自己本身,所以累加的和肯定是1。对于非素数,我们首先找到它的最小整数因子,例如28,最小整数因子是2,表示[2,14]是其中一对整数因子;接下来对较大的那个整数因子继续做最小整数因子的分解,14表示成[2,7],再用上一次分解中较小的整数因子乘以本次分解中较小的整数因子,就是第二对整数因子,这里是[2*2,7],而后继续分解较大的整数因子,只到无法被分解为止(即这个数是素数为止)。到这里就可以得到这个整数的所有整数因子对,求和即可,注意不要忘了加上数字1。

代码如下:

import math
class Solution(object):
    def is_prime(self,num):
        if num == 1 or num == 2:
            return True
        for i in range(2, int(math.sqrt(num) + 1)):
            if num % i == 0:
                return False
        return True

    def checkPerfectNumber(self, num):
        if num < 0 or num == 1:
            return False
        v1 = 1
        v2 = num
        count = 1
        while self.is_prime(v2) == False:
            tmp = v2
            tmp1 = v1
            j = 1
            while j < tmp:
                j += 1
                if tmp % j == 0:
                    v1 = min(j, tmp / j)
                    v2 = max(j, tmp / j)
                    v1 = tmp1 * v1
                    count += v1
                    count += v2
                    break
        return count == num

转载于:https://www.cnblogs.com/seyjs/p/8715892.html

原文地址:https://www.cnblogs.com/twodog/p/12137174.html