LeetCode 题解工作台
三除数
给你一个整数 n 。如果 n 恰好有三个正除数 ,返回 true ;否则,返回 false 。 如果存在整数 k ,满足 n = k * m ,那么整数 m 就是 n 的一个 除数 。 示例 1: 输入: n = 2 输出: false 解释: 2 只有两个除数:1 和 2 。 示例 2: 输入: …
3
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数学·结合·enumeration
答案摘要
一个数 一定有 和 两个正除数,因此只需要枚举 到 之间的数,看它们是否是 的正除数即可,是则累加计数器,最后判断计数器是否为 即可。 时间复杂度 ,空间复杂度 。其中 为给定的整数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·结合·enumeration 题型思路
题目描述
给你一个整数 n 。如果 n 恰好有三个正除数 ,返回 true ;否则,返回 false 。
如果存在整数 k ,满足 n = k * m ,那么整数 m 就是 n 的一个 除数 。
示例 1:
输入:n = 2 输出:false 解释:2 只有两个除数:1 和 2 。
示例 2:
输入:n = 4 输出:true 解释:4 有三个除数:1、2 和 4 。
提示:
1 <= n <= 104
解题思路
方法一:枚举
一个数 一定有 和 两个正除数,因此只需要枚举 到 之间的数,看它们是否是 的正除数即可,是则累加计数器,最后判断计数器是否为 即可。
时间复杂度 ,空间复杂度 。其中 为给定的整数。
class Solution:
def isThree(self, n: int) -> bool:
return sum(n % i == 0 for i in range(2, n)) == 1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
This problem tests understanding of divisors and properties of numbers.
- question_mark
Look for efficient approaches that minimize unnecessary calculations.
- question_mark
The candidate should recognize patterns in the number's divisors and use optimizations such as prime checking.
常见陷阱
外企场景- error
Forgetting that n must be the square of a prime number to have exactly three divisors.
- error
Incorrectly counting the divisors of non-perfect squares.
- error
Missing optimizations that improve runtime, such as only checking divisors up to √n.
进阶变体
外企场景- arrow_right_alt
Test with larger values of n, such as 10^4.
- arrow_right_alt
Consider n values that are squares of prime numbers.
- arrow_right_alt
Examine cases where n has more than three divisors.