507.圆满数(javascript)507.PerfectNumber
原创对于一个 正整数,如果它和除自身以外的所有 正因子 总和相等,我们称之为 “完美数字”。
给定一个 整数 n, 如果是一个完美的数字,请返回 true; 否则返回 false。
A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly.
Given an integer n, return true if n is a perfect number, otherwise return false.
示例 1:
输入:num = 28
输出:true
解释:28 = 1 + 2 + 4 + 7 + 14
1, 2, 4, 7, 和 14 是 28 在所有积极因素中。
示例 2:
输入:num = 7
输出:false
Example 1:
Input: num = 28
Output: true
Explanation: 28 = 1 + 2 + 4 + 7 + 14
1, 2, 4, 7, and 14 are all divisors of 28.
Example 2:
Input: num = 7
Output: false
解决问题的思路:
- 除了它自己,什么都要得到。 积极因素,包括1
- 减少遍历的范围,只需要 i <= √num就可以了
-
枚举时,我们只需要枚举 √num 数字。这是因为如果 √num 存在大于√num 的因数 d,则必须具有小于√num的因数√num/d
var checkPerfectNumber = function (num) { if (num === 1) { return false } let sqrtMum = Math.floor(Math.sqrt(num)) let sum = 1 for (let i = 2; i <= sqrtMum; i++) { if (num % i == 0) { sum += i + Math.floor(num / i); }
} return sum === num};
leetcode: https://leetcode-cn.com/problems/perfect-number/
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
itfan123


