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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值