1952. 三除数
给你一个整数 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 。
1952. Three Divisors
Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false.
An integer m is a divisor of n if there exists an integer k such that n = k * m.
Example 1:
Input: n = 2
Output: false
Explantion: 2 has only two divisors: 1 and 2.
Example 2:
Input: n = 4
Output: true
Explantion: 4 has three divisors: 1, 2, and 4.
题目就是要我们找一个正好被整除的
我们最想到的就是遍历即可 然后一个计数的
另一个方法就是其实就是找1到sqrt(n)之间的数字然后做一个判断
class Solution:
def isThree(self, n: int) -> bool:
t=0
for i in range(n):
if n % (i+1) == 0:
t+=1
if t == 3:
return True
return False
class Solution:
def isThree(self, n: int) -> bool:
# t=0
# for i in range(n):
# if n % (i+1) == 0:
# t+=1
# if t == 3:
# return True
# return False
cnt=0
i=1
while i<=sqrt(n):
if n%i==0:
if n / i == i:
cnt+=1
elif n/i!=i:
cnt+=2
i+=1
if cnt ==3:
return True
return False
if cnt ==3:
return True
return False
优化:
return cnt ==3
执行结果: 通过 显示详情 查看示例代码 添加备注
执行用时: 28 ms , 在所有 Python3 提交中击败了 97.80% 的用户 内存消耗: 15 MB , 在所有 Python3 提交中击败了 9.89% 的用户 通过测试用例: 228 / 228