【每日一题20220520】质数与否

:mage:‍ 质数是指在大于1的自然数中,除了1和它本身以外不再有其他因数的自然数。给定一个数字,请编写一个函数,判断它是否为质数。

【示例】
输入:7
输出:True
解释:数字7,只能被1和7整除

题目难度:简单
题目来源:codewars-Is a number prime?

def solution(n: int)-> bool:
    # your code here

assert solution(7) is True
assert solution(5099) is True
assert solution(45) is False
def solution(n: int) -> bool:
    # your code here
    if n > 1:
        for i in range(2, n):
            if n % i == 0:
                return False
        else:
            return True
    else:
        return False


assert solution(7) is True
assert solution(5099) is True
assert solution(45) is False

上述写法能判断质数但是CodeWars超时,优化了下。

def solution(n: int) -> bool:
    # your code here
    if n > 1:
        i = 2
        while i * i <= n:
            if n % i == 0:
                return False
            i += 1
        return True
    else:
        return False


assert solution(7) is True
assert solution(5099) is True
assert solution(45) is False
def solution(n: int)-> bool:
    # your code here
    flag = 2
    while flag < n:
        if n % flag == 0:
            return False
        flag += 1
    return True

assert solution(7) is True
assert solution(5099) is True
assert solution(45) is False

def solution(n: int)-> bool:
    num=[]
    for i in range(1,n+1):
        if n%i==0:
            num.append(i)
    return False if len(num)>2 else True
def solution(n: int)-> bool:
import math
    if n< 2 or  (n>2 and n%2 == 0):
        return False
    else:
      
        for i in range(3,int(math.sqrt(n))+1,2):
            if n%i ==0:
                return False
        return True
def solution(n: int)-> bool:
    if n>1:
        for i in range(2,n):
            if n%i==0:
                return False
        return True
    else:
        return False

assert solution(7) is True
assert solution(5099) is True
assert solution(45) is False
def solution(n: int)-> bool:
    # your code here
    if n == 1:
        return True
    for i in range(2, n // 2 + 1):
        if n % i == 0:
            return False
    else:
        return True


assert solution(7) is True
assert solution(5099) is True
assert solution(45) is False
assert solution(2) is True

def solution(n: int)-> bool:
    for i in range(2,n):
        if n%i == 0:
            return False
    return True
assert solution(7) is True
assert solution(5099) is True
assert solution(45) is False
assert solution(2) is True
assert solution(1) is True
def solution(n: int)-> bool:
    for i in range(2,n):
        if n%i==0:
            return False
    return True

assert solution(7) is True
assert solution(5099) is True
assert solution(45) is False