Skip to content

Instantly share code, notes, and snippets.

@shai-almog
Created October 19, 2021 09:00
Show Gist options
  • Save shai-almog/8c8bbbb4297f758f7ce1d5f7a4cc1c74 to your computer and use it in GitHub Desktop.
Save shai-almog/8c8bbbb4297f758f7ce1d5f7a4cc1c74 to your computer and use it in GitHub Desktop.
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