LeetCode 507. Perfect Number

perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly.

Given an integer n, return true if n is a perfect number, otherwise return false.

 

Example 1:

Input: num = 28
Output: true
Explanation: 28 = 1 + 2 + 4 + 7 + 14
1, 2, 4, 7, and 14 are all divisors of 28.

Example 2:

Input: num = 6
Output: true

Example 3:

Input: num = 496
Output: true

Example 4:

Input: num = 8128
Output: true

Example 5:

Input: num = 2
Output: false

 

Constraints:

  • 1 <= num <= 108

这道题看似简单,实际上不使用欧几里得-欧拉定律的话Python是会超过判断时间的。

最简单的暴力索引:

class Solution(object):
    def checkPerfectNumber(self, num):
        """
        :type num: int
        :rtype: bool
        """
        sum = 0
        i = 1
        while i*2 <= num:
            if num%i == 0:
                sum = sum+i
            i = i+1
        if num == sum:
            return True
        
        return False

超时了,然后优化一下,还是超时了:

class Solution(object):
    def checkPerfectNumber(self, num):
        """
        :type num: int
        :rtype: bool
        """
        
        sum = 1
        i = 2
        while i*i < num:
            if num%i == 0:
                sum = sum+i
                quotient = num/i
                sum = sum+quotient
            i = i+1
        if i*i == num:
            sum = sum+i
        if num == sum:
            return True
        
        return False

最后使用欧几里得-欧拉公式完成:

class Solution(object):
    def checkPerfectNumber(self, num):
        """
        :type num: int
        :rtype: bool
        """
        primes = [2, 3, 5, 7, 13, 17, 19, 31]
        for prime in primes:
            pn = (1<<(prime-1))*((1<<prime)-1)
            if pn == num:
                return True
        
        return False

C++版本

class Solution {
public:
    bool checkPerfectNumber(int num) {
        vector<long> primes{2, 3, 5, 7, 13, 17, 19, 31};
        for (long prime:primes) {
            long pn = long(1<<prime-1)*(long(1<<prime)-1);
            if (pn == num) {
                return true;
            }
        }
        return false;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值