LeetCode 题解工作台

完美数

对于一个 正整数 ,如果它和除了它自身以外的所有 正因子 之和相等,我们称它为 「完美数」 。 给定一个 整数 n , 如果是完美数,返回 true ;否则返回 false 。 示例 1: 输入: num = 28 输出: true 解释: 28 = 1 + 2 + 4 + 7 + 14 1, 2,…

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·driven

bolt

答案摘要

我们首先判断 是否为 1,如果为 1,则 不是完美数,返回 。 然后,我们从 2 开始枚举 的所有正因子,如果 能被 的某个正因子 整除,那么我们将 加入到答案 中。如果 除以 得到的商不等于 ,我们也将 除以 得到的商加入到答案 中。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

给定一个 整数 n, 如果是完美数,返回 true;否则返回 false

 

示例 1:

输入:num = 28
输出:true
解释:28 = 1 + 2 + 4 + 7 + 14
1, 2, 4, 7, 和 14 是 28 的所有正因子。

示例 2:

输入:num = 7
输出:false

 

提示:

  • 1 <= num <= 108
lightbulb

解题思路

方法一:枚举

我们首先判断 num\textit{num} 是否为 1,如果为 1,则 num\textit{num} 不是完美数,返回 false\text{false}

然后,我们从 2 开始枚举 num\textit{num} 的所有正因子,如果 num\textit{num} 能被 num\textit{num} 的某个正因子 ii 整除,那么我们将 ii 加入到答案 s\textit{s} 中。如果 num\textit{num} 除以 ii 得到的商不等于 ii,我们也将 num\textit{num} 除以 ii 得到的商加入到答案 s\textit{s} 中。

最后,我们判断 s\textit{s} 是否等于 num\textit{num} 即可。

时间复杂度 O(n)O(\sqrt{n}),其中 nnnum\textit{num} 的大小。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
    def checkPerfectNumber(self, num: int) -> bool:
        if num == 1:
            return False
        s, i = 1, 2
        while i <= num // i:
            if num % i == 0:
                s += i
                if i != num // i:
                    s += num // i
            i += 1
        return s == num
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate efficiently uses the math-driven approach to check divisors.

  • question_mark

    The solution avoids unnecessary loops and optimizes divisor checks.

  • question_mark

    The candidate applies the square root optimization for improved performance.

warning

常见陷阱

外企场景
  • error

    Forgetting to exclude the number itself from the sum of divisors.

  • error

    Not optimizing by checking divisors only up to sqrt(n).

  • error

    Handling large numbers without considering time and space efficiency.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Check for perfect numbers in a range of numbers, not just a single number.

  • arrow_right_alt

    Return the smallest perfect number in a given range.

  • arrow_right_alt

    Extend the problem to find perfect numbers for larger constraints, such as n up to 10^9.

help

常见问题

外企场景

完美数题解:数学·driven | LeetCode #507 简单