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

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必定大于1。其实这道题跟之前的判断质数的题蛮类似的,都是要找因子。由于1肯定是因子,可以提前加上,那么我们找其他因子的范围是[2, sqrt(n)]。我们遍历这之间所有的数字,如果可以被n整除,那么我们把i和num/i都加上,对于n如果是平方数的话,那么我们此时相同的因子加来两次,所以我们要减掉一次。还有就是在遍历的过程中如果累积和sum大于n了,直接返回false即可。在循环结束后,我们看sum是否和num相等,参见代码如下:

解法一:

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;
    }
};

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

解法二:

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

参考资料:

https://discuss.leetcode.com/topic/84259/simple-java-solution

本文转自博客园Grandyang,原文链接:[LeetCode] Perfect Number 完美数字

,如需转载请自行联系原博主。

相关文章
|
7月前
|
算法
Leetcode 313. Super Ugly Number
题目翻译成中文是『超级丑数』,啥叫丑数?丑数就是素因子只有2,3,5的数,7 14 21不是丑数,因为他们都有7这个素数。 这里的超级丑数只是对丑数的一个扩展,超级丑数的素因子不再仅限于2 3 5,而是由题目给定一个素数数组。与朴素丑数算法相比,只是将素因子变了而已,解法还是和朴素丑数一致的。
72 1
|
15天前
|
存储 SQL 算法
LeetCode 题目 65:有效数字(Valid Number)【python】
LeetCode 题目 65:有效数字(Valid Number)【python】
|
1月前
|
存储 算法
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
15 0
|
7月前
|
存储
Leetcode Single Number II (面试题推荐)
给你一个整数数组,每个元素出现了三次,但只有一个元素出现了一次,让你找出这个数,要求线性的时间复杂度,不使用额外空间。
25 0
The Preliminary Contest for ICPC China Nanchang National Invitational A题 PERFECT NUMBER PROBLEM
The Preliminary Contest for ICPC China Nanchang National Invitational A题 PERFECT NUMBER PROBLEM
53 0
LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
|
存储 前端开发 算法
LeetCode只出现一次的数字使用JavaScript解题|前端学算法
LeetCode只出现一次的数字使用JavaScript解题|前端学算法
115 0
|
算法 PHP
力扣(LeetCode)算法题解:1365. 有多少小于当前数字的数字
力扣(LeetCode)算法题解:1365. 有多少小于当前数字的数字
115 0
|
算法 PHP
力扣(LeetCode)算法题解:1323. 6 和 9 组成的最大数字
力扣(LeetCode)算法题解:1323. 6 和 9 组成的最大数字
114 0
|
算法 PHP
力扣(LeetCode)算法题解:1295. 统计位数为偶数的数字
力扣(LeetCode)算法题解:1295. 统计位数为偶数的数字
95 0