[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.
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)
定义Perfect Number是一个正整数,它等于除了它自己之外的所有正除数的总和。现在,给定一个整数n,编写一个函数,当它是一个完美数字时返回true,否则返回false。
解法:直接解就可以。注意处理num是1的时候。还有技巧是,只计算num/2就可以,如果能整除就把除数和结果都累加。
Java:
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:
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:
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++:
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; } };