Skip to content

Instantly share code, notes, and snippets.

@mburke05
Created November 6, 2015 19:14
Show Gist options
  • Save mburke05/56dd769f2e48581139f6 to your computer and use it in GitHub Desktop.
Save mburke05/56dd769f2e48581139f6 to your computer and use it in GitHub Desktop.
from math import floor, sqrt
def find_next_prime(n):
""" We use is_prime passed through a while loop to check if a given value (starting at n+1) is_prime
and exit if we've found our number. I think this too can be accomplished potentially using itertools to
greater effect and would love to hear criticism. I know that while True conditionals are generally frowned upon
in python."""
i = n+1
while True:
if is_prime(i):
return i
i+=1
def is_prime(n):
""" The sqrt of an integer n is the highest point of a possible paired factor for n (e.g. n**1/2 * n**1/2),
so we start at the integer 2 and work our way up to the floor of the square root. If the modulo of n by any number
i in this range is = to 0 we know the number cannot be prime. There are more efficient ways of doing this calculation
including vectorisation in numpy, but I am unfortunately not so mathematically gifted :)."""
for i in xrange(2,int(floor(sqrt(n)))+1):
if not n % i:
return False
return True
[(x, is_prime(x)) for x in xrange(2,12)]
[find_next_prime(6),
find_next_prime(10),
find_next_prime(11),
find_next_prime(200),
find_next_prime(2000),
find_next_prime(200000)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment