对于一个 正整数,如果它和除了它自身以外的所有 正因子 之和相等,我们称它为 「完美数」。

给定一个 整数 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,1428 的所有正因子。

示例 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. 获取除了它自身以外的所有 正因子,包括1
  2. 缩小遍历范围,只需要 i <= √num就可以了
  3. 在枚举时,我们只需要枚举不超过 √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/

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐