[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)

完美数字。

题意是给一个正整数数字N,问这个数字是否是一个完美数字。完美数字N的定义是N可以是其所有大于0的除数的加和。

因为涉及到除数,所以需要遍历的范围一定不会大于sqrt(N)。思路是遍历从2到num的平方根,num能被i整除,说明i和num / i都是num的公因数,所以都加到结果集里面。退出循环后,判断res(公因数的加和)是否等于num。

时间O(sqrt(num))

空间O(1)

Java实现

 1 class Solution {
 2     public boolean checkPerfectNumber(int num) {
 3         // corner case
 4         if (num == 1) {
 5             return false;
 6         }
 7 
 8         // normal case
 9         int res = 1;
10         for (int i = 2; i < Math.sqrt(num); i++) {
11             if (num % i == 0) {
12                 res += i + num / i;
13             }
14         }
15         return res == num;
16     }
17 }

JavaScript实现

 1 /**
 2  * @param {number} num
 3  * @return {boolean}
 4  */
 5 var checkPerfectNumber = function(num) {
 6     // corner case
 7     if (num === 1) {
 8         return false;
 9     }
10 
11     // normal case
12     let res = 1;
13     for (let i = 2; i <= Math.sqrt(num); i++) {
14         if (num % i === 0) {
15             res += i + Math.floor(num / i);
16         }
17     }
18     return res === num;
19 };

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/11756368.html