LeetCode 题解工作台
完美数
对于一个 正整数 ,如果它和除了它自身以外的所有 正因子 之和相等,我们称它为 「完美数」 。 给定一个 整数 n , 如果是完美数,返回 true ;否则返回 false 。 示例 1: 输入: num = 28 输出: true 解释: 28 = 1 + 2 + 4 + 7 + 14 1, 2,…
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数学·driven
答案摘要
我们首先判断 是否为 1,如果为 1,则 不是完美数,返回 。 然后,我们从 2 开始枚举 的所有正因子,如果 能被 的某个正因子 整除,那么我们将 加入到答案 中。如果 除以 得到的商不等于 ,我们也将 除以 得到的商加入到答案 中。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路
题目描述
对于一个 正整数,如果它和除了它自身以外的所有 正因子 之和相等,我们称它为 「完美数」。
给定一个 整数 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
解题思路
方法一:枚举
我们首先判断 是否为 1,如果为 1,则 不是完美数,返回 。
然后,我们从 2 开始枚举 的所有正因子,如果 能被 的某个正因子 整除,那么我们将 加入到答案 中。如果 除以 得到的商不等于 ,我们也将 除以 得到的商加入到答案 中。
最后,我们判断 是否等于 即可。
时间复杂度 ,其中 为 的大小。空间复杂度 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.