当前位置:网站首页>The third divisor of leetcode simple question

The third divisor of leetcode simple question

2022-04-23 08:14:00 ·Starry Sea

subject

Give you an integer n . If n There are exactly three positive divisors , return true ; otherwise , return false .
If there are integers k , Satisfy n = k * m , So integers m Namely n One of the Divisor .
Example 1:
Input :n = 2
Output :false
explain :2 There are only two divisors :1 and 2 .
Example 2:
Input :n = 4
Output :true
explain :4 There are three divisors :1、2 and 4 .
Tips :
1 <= n <= 10^4
source : Power button (LeetCode)

Their thinking

   First of all, a number must have more than two divisors, which is 1 And itself , We can set up a flag when 2 and n-1 Found a divisor between , So conversion tag , If the divisor is encountered again, the check mark can return the result , In addition, if you don't encounter divisor , It shows that this number is a prime number and can also return the result .

class Solution:
    def isThree(self, n: int) -> bool:
        if n==2:
            return False
        flag=False
        for i in range(2,n):
            if n%i==0:
                if flag:
                    return False
                flag=True
        return flag

 Insert picture description here
   Actually, a number with three divisors , One is 1 The other is itself , There is also a pair of divisors that must be equal . But finding this logarithm must start from 2 Start looking for , This is not biased .

class Solution:
    def isThree(self, n: int) -> bool:
        for i in range(2,int(n**0.5)+1):
            if n%i==0:
                return i**2==n
        return False

 Insert picture description here

版权声明
本文为[·Starry Sea]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230701590377.html