From fdc8a5bac5e2e4999a889bdcc1948552183a1ccb Mon Sep 17 00:00:00 2001 From: daviddoji Date: Sat, 3 Jul 2021 16:54:47 +0200 Subject: [PATCH] Add function to list primes --- src/Python/utils.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/Python/utils.py b/src/Python/utils.py index 62a3602..644c294 100644 --- a/src/Python/utils.py +++ b/src/Python/utils.py @@ -16,11 +16,29 @@ def timeit(name): return profile - def is_prime(n): if n % 2 == 0 and n > 2: return False for i in range(3, int(math.sqrt(n)) + 1, 2): if n % i == 0: return False - return True \ No newline at end of file + 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] \ No newline at end of file