Skip to content

Instantly share code, notes, and snippets.

@dwalleck
Created June 14, 2019 17:02
Show Gist options
  • Save dwalleck/4809baed3cc047af8b3ba7afa34e1671 to your computer and use it in GitHub Desktop.
Save dwalleck/4809baed3cc047af8b3ba7afa34e1671 to your computer and use it in GitHub Desktop.
Prints the first N primes
import math
import sys
def is_prime(a):
"""
https://stackoverflow.com/questions/1801391/what-is-the-best-algorithm-for-checking-if-a-number-is-prime
"""
if a < 2:
return False
elif a !=2 and a % 2 == 0:
return False
else:
return all(a % i for i in range(3, int(a**0.5)+1))
def generate_until(func, inputs, size):
outputs = []
for i in inputs:
if func(i):
outputs.append(i)
if len(outputs) == size:
return outputs
raise Exception('Unable to generate a list of results with the required size.')
# Prints the first 13 primes
print(generate_until(is_prime, range(2, sys.maxsize), 13))
# Fails if the range is too small
try:
generate_until(is_prime, range(2, 10), 13)
except Exception as ex:
print(ex)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment