python simple solution


  • 0
    Z
    class Solution(object):
        def checkPerfectNumber(self, num):
            """
            :type num: int
            :rtype: bool
            """
            if num < 2:
                return False
            total = -num
            for i in xrange(1, num):
                if i * i > num:
                    break
                if num % i == 0:
                    total += i + num / i
                    if num / i == i:
                        total -= i
            return total == num
    

  • 0
    Z

    @zqfan I don't see why you need that nested if statement with in num%1, since you just trying to handle the case which num / i == i, you can just change if i * i > num to if i * i >= num. Here is a simplified version.

    class Solution(object):
        def checkPerfectNumber(self, num):
            total, i = 1, 2
            while i * i < num:
                if num % i == 0:
                    total += i + num / i
                i += 1
            return num > 1 and total == num or False

  • 0
    C

    @zhongyuan9817 Mine didn't work unless I changed the number to int.

    def first(num):
    num = int(num)
    total, i = 1, 2
    while i * i < num:
    if num % i == 0:
    total += i
    total += num / i
    i += 1
    return num > 1 and total == num or False
    Thanks for the solution


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.