[LeetCode] 507. Perfect Number 完美数字

2021年09月15日 阅读数:1
这篇文章主要向大家介绍[LeetCode] 507. Perfect Number 完美数字,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.html

Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not. java

Example:python

Input: 28
Output: True
Explanation: 28 = 1 + 2 + 4 + 7 + 14

Note: The input number n will not exceed 100,000,000. (1e8)函数

定义Perfect Number是一个正整数,它等于除了它本身以外的全部正除数的总和。如今,给定一个整数n,编写一个函数,当它是一个完美数字时返回true,不然返回false。post

解法:直接解就能够。注意处理num是1的时候。还有技巧是,只计算num/2就能够,若是能整除就把除数和结果都累加。url

Java:htm

public class Solution {
    public boolean checkPerfectNumber(int num) {
        if (num == 1) return false;
        
        int sum = 0;
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
                sum += i + num / i;
            }
        }
        sum++;
        
        return sum == num;
    }
}

Python:blog

class Solution(object):
    def checkPerfectNumber(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num <= 0: return False
        ans, SQRT = 0, int(num ** 0.5)
        ans = sum(i + num//i for i in range(1, SQRT+1) if not num % i)
        if num == SQRT ** 2: ans -= SQRT
        return ans - num == num    

Python:get

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

        return True if s == num else False  

C++:input

class Solution {
public:
    bool checkPerfectNumber(int num) {
        if (num == 1) return false;
        int sum = 1;
        for (int i = 2; i * i <= num; ++i) {
            if (num % i == 0) sum += (i + num / i);
            if (i * i == num) sum -= i;
            if (sum > num) return false;
        }
        return sum == num;
    }
};  

C++:

class Solution {
public:
    bool checkPerfectNumber(int num) {
        return num==6 || num==28 || num==496 || num==8128 || num==33550336;
    }
};

  

 

All LeetCode Questions List 题目汇总