Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Prime number calculator used as part of a debugging tutorial on talktotheduck.dev
import math
import time
import six
if six.PY2:
# In python2, range returns a list instead of an iterator. When running on a large range,
# this can take up all of the available memory and crash the process.
range = xrange
def isPrime(num):
if num == 2:
return True
if num < 2 or num % 2 == 0:
return False
sqrt_num = int(math.sqrt(num))
for i in range(3, sqrt_num + 1, 2):
if num % i == 0:
return False
return True
def main():
print("Calculating number of primes")
cnt = 0
start = time.time()
for i in range(2, 10 ** 9):
if isPrime(i):
cnt += 1
print("Total number of primes: ", cnt)
print("Took ", time.time() - start, " seconds")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment