LeetCode 题解工作台

三除数

给你一个整数 n 。如果 n 恰好有三个正除数 ,返回 true ;否则,返回 false 。 如果存在整数 k ,满足 n = k * m ,那么整数 m 就是 n 的一个 除数 。 示例 1: 输入: n = 2 输出: false 解释: 2 只有两个除数:1 和 2 。 示例 2: 输入: …

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·结合·enumeration

bolt

答案摘要

一个数 一定有 和 两个正除数,因此只需要枚举 到 之间的数,看它们是否是 的正除数即可,是则累加计数器,最后判断计数器是否为 即可。 时间复杂度 ,空间复杂度 。其中 为给定的整数。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数 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
lightbulb

解题思路

方法一:枚举

一个数 nn 一定有 11nn 两个正除数,因此只需要枚举 22n1n-1 之间的数,看它们是否是 nn 的正除数即可,是则累加计数器,最后判断计数器是否为 11 即可。

时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)。其中 nn 为给定的整数。

1
2
3
4
class Solution:
    def isThree(self, n: int) -> bool:
        return sum(n % i == 0 for i in range(2, n)) == 1
speed

复杂度分析

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

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

三除数题解:数学·结合·enumeration | LeetCode #1952 简单