[LeetCode] 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:post

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

 

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

 

这道题让咱们判断给定数字是否为完美数字,并给来完美数字的定义,就是一个整数等于除其自身以外的全部的因子之和。那么因为不能包含自身,因此n一定大于1。其实这道题跟以前的判断质数的题蛮相似的,都是要找因子。因为1确定是因子,能够提早加上,那么咱们找其余因子的范围是[2, sqrt(n)]。咱们遍历这之间全部的数字,若是能够被n整除,那么咱们把i和num/i都加上,对于n若是是平方数的话,那么咱们此时相同的因子加来两次,因此咱们要判断一下,若是相等,就再也不加 num/i。实际上,符合要求的完美数字不多,根本就没有彻底平方数,咱们根本就不用担忧会加两次,固然,这都是从结果分析的,为了严格按照题目的要求,仍是加上判断吧。还有就是咱们也能够在遍历的过程当中若是累积和sum大于n了,直接返回false,可是感受加了也没咋提升运行时间,因此干脆就不加了。在循环结束后,咱们首先判断num是否为1,由于题目中说了不能加包括自己的因子,而后咱们再看sum是否和num相等,参见代码以下:spa

 

解法一:code

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

 

下面这种方法叼的不行,在给定的n的范围内其实只有五个符合要求的完美数字,因而就有这种枚举的解法,那么套用一句诸葛孔明的名言就是,我从未见过如此厚颜无耻之解法。哈哈,开个玩笑。写这篇博客的时候,国足正和伊朗进行十二强赛,上半场0比0,但愿国足下半场能进球,好运好运,不忘初心,方得始终~htm

 

解法二:blog

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

 

相似题目:leetcode

Self Dividing Numbersget

 

参考资料:

https://leetcode.com/problems/perfect-number/

https://leetcode.com/problems/perfect-number/discuss/98594/simple-java-solution

 

LeetCode All in One 题目讲解汇总(持续更新中...)

相关文章
相关标签/搜索