检查素数【难度:1级】:
答案1:
def is_prime(n):
return n > 1 and all(n % i for i in xrange(2, n))
答案2:
def is_prime(n):
'Return True if n is a prime number otherwise return False'
return n > 1 and all(n % i for i in xrange(2, n))
答案3:
import math
def is_prime(n):
if n < 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
答案4:
def is_prime(n):
'Return True if n is a prime number otherwise return False'
if n < 2:
return False
if n == 2:
return True
if not n & 1:
return False
for i in range(3, n):
if (n % i) == 0 and n != i:
return False
return True
答案5:
def is_prime(n):
'Return True if n is a prime number otherwise return False'
return n > 1 and not any(n % x == 0 for x in xrange(2, int(n**0.5)+1))
答案6:
def is_prime(n):
'Return True if n is a prime number otherwise return False'
if n <=1: return False
return all(n % i for i in xrange(2, n))
答案7:
def is_prime(n):
if n <= 1:
return False
return all(n % i for i in xrange(2, n))
答案8:
def is_prime(n):
"""Return True if n is a prime number otherwise return False"""
return n > 1 and all(n % i for i in xrange(int(n ** 0.5), 1, -1))
答案9:
def is_prime(num):
'Return True if n is a prime number otherwise return False'
return num > 1 and not any(num % n == 0 for n in range(2, num))
答案10:
def is_prime(num):
return num > 1 and not any(num % n == 0 for n in range(2,num))
答案11:
from math import sqrt
def is_prime(n):
if n < 2:
return False
elif n == 2:
return True
elif n % 2 == 0:
return False
else:
for i in range(3, int(sqrt(n)) + 1, 2):
if n % i == 0:
return False
else:
return True
答案12:
def is_prime(n):
if n < 2:
return False
for i in range(3, int(n**0.5)+1, 2):
if n%i == 0:
return False
return True
答案13:
def is_prime(n):
if n == 2:
return True
if n % 2 == 0 or n == 1:
return False
return all(n % i != 0 for i in range(3, int(n**0.5) + 1, 2))