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)


题目标签:Math

  题目给了我们一个 num,让我们找出 num 的所有 divisors 的累加 是否 等于 num。这里所有的divisors 不包括重复的。

  可以从2 开始遍历,一旦 i * i > num 跳出遍历:

    对于每一个 i,如果 num % i == 0 的话,就把2个 divisors 累加;

    如果2个 divisors 是一样的话,那么 减去一个 i;

  以 i * i  <= num 为边界 是因为 如果有2个不同的 divisors,肯定是一个小,一个大,那么就是一个在边界左边,一个在边界右边,既然我们把2个divisors都累加了,所以我们只需要走完左边的部分就可以了,不需要再去走右边部分了。

  

Java Solution:

Runtime beats 56.59% 

完成日期:06/17/2017

关键词:math

关键点:只需要遍历 (i =2; i*i <= num; i++) 的部分

class Solution 
{
    public boolean checkPerfectNumber(int num) 
    {
        if(num < 2)
            return false;
        
        int sum_divisors = 1; 
        
        for(int i=2; i*i <= num; i++) // start from 2 to square root of num
        {
            if(num % i == 0) // if find the divisors, add both ones into sum
                sum_divisors += i + num / i;
            
            if(i*i == num) // if both divisors are same, minus one
                sum_divisors -= i;
            
        }
        
        
        return sum_divisors == num;
    }
    
    
}

参考资料:http://www.cnblogs.com/grandyang/p/6636879.html

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

原文地址:https://www.cnblogs.com/jimmycheng/p/8440650.html