Skip to content

Instantly share code, notes, and snippets.

@tonyslowdown
Last active September 13, 2016 23:06
Show Gist options
  • Save tonyslowdown/8cdb23f5aeab5539544d5d7764ac1af6 to your computer and use it in GitHub Desktop.
Save tonyslowdown/8cdb23f5aeab5539544d5d7764ac1af6 to your computer and use it in GitHub Desktop.
'''
Sieve is good for pre-generating list of primes, so that you can check quickly if a number is prime or not.
If you're checking if a single number is a prime or not, use the looping method
'''
import math
def generate_primes_sieve(n):
non_primes = set()
for i in range(2, n+1):
if i not in non_primes:
yield i
for j in range(i**2, n+1, i):
non_primes.add(j)
def get_primes_sieve(n):
primes = []
non_primes = set()
for i in range(2, n+1):
if i not in non_primes:
primes.append(i)
for j in range(i**2, n+1, i):
non_primes.add(j)
return primes
def is_prime_sieve(n):
if n < 2:
return False
for prime_number in generate_primes_sieve(int(math.sqrt(n))):
if n % prime_number == 0:
return False
return True
def is_prime_loop(n):
if n < 2:
return False
for x in range(2, int(math.sqrt(n))+1):
if n % x == 0:
return False
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment