Add function to list primes
This commit is contained in:
parent
24835a4496
commit
fdc8a5bac5
@ -16,11 +16,29 @@ def timeit(name):
|
|||||||
return profile
|
return profile
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def is_prime(n):
|
def is_prime(n):
|
||||||
if n % 2 == 0 and n > 2:
|
if n % 2 == 0 and n > 2:
|
||||||
return False
|
return False
|
||||||
for i in range(3, int(math.sqrt(n)) + 1, 2):
|
for i in range(3, int(math.sqrt(n)) + 1, 2):
|
||||||
if n % i == 0:
|
if n % i == 0:
|
||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
# Returns a list of True and False indicating whether each number is prime.
|
||||||
|
# For 0 <= i <= n, result[i] is True if i is a prime number, False otherwise.
|
||||||
|
def list_primality(n):
|
||||||
|
# Sieve of Eratosthenes
|
||||||
|
result = [True] * (n + 1)
|
||||||
|
result[0] = result[1] = False
|
||||||
|
for i in range(int(math.sqrt(n) + 1)):
|
||||||
|
if result[i]:
|
||||||
|
for j in range(i * i, len(result), i):
|
||||||
|
result[j] = False
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
# Returns all the prime numbers less than or equal to n, in ascending order
|
||||||
|
# For example: list_primes(97) = [2, 3, 5, 7, 11, ..., 83, 89, 97].
|
||||||
|
def list_primes(n):
|
||||||
|
return [i for (i, is_prime) in enumerate(list_primality(n)) if is_prime]
|
Loading…
x
Reference in New Issue
Block a user