diff --git a/e007.py b/e007.py index 9e95673..e006570 100644 --- a/e007.py +++ b/e007.py @@ -26,6 +26,14 @@ def is_prime(n): f = f + 6 return True +def prime_generator(): + i = 1 + yield 2 + while True: + i += 2 + if is_prime(i): + yield i + def primes(max_count = 0, max_value = 0): if not max_count and not max_value: raise Exception('There must be a constraint on how many primes to return!') @@ -39,8 +47,15 @@ def primes(max_count = 0, max_value = 0): return primes def main(): - print '6th Prime', primes(6)[-1] - print '10001st Prime', primes(10001)[-1] + i = 0 + prime = 0 + generator = prime_generator() + while i < 10000: + i += 1 + prime = generator.next() + if i == 6: + print '6th Prime', prime + print '10001st Prime', prime if __name__ == '__main__': main() diff --git a/e010.py b/e010.py index c35677d..6a2e4fb 100644 --- a/e010.py +++ b/e010.py @@ -4,12 +4,18 @@ The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. """ -from e007 import primes; +from e007 import prime_generator def main(): print 'Fetching all primes for n < 2,000,000' - p = primes(0, 2000000) - print 'Sum:', sum(p) + total = 0 + generator = prime_generator() + while True: + prime = generator.next() + if prime >= 2000000: + break + total += prime + print 'Sum:', total if __name__ == '__main__': main() diff --git a/e035.py b/e035.py index 4bfb312..54719b7 100644 --- a/e035.py +++ b/e035.py @@ -6,7 +6,7 @@ There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73 How many circular primes are there below one million? """ -from e007 import primes +from e007 import is_prime, prime_generator class NotCircular(Exception): pass @@ -30,10 +30,10 @@ def cyclic_rotation(n): def main(): MAX = 1000000 circular_primes = [] - print 'Generating primes for p < {0}...'.format(MAX) - prime_list = primes(0, MAX) - print 'Searching for circular primes...' - for prime in prime_list: + print 'Searching for circular primes for p < {0}...'.format(MAX) + for prime in prime_generator(): + if prime >= MAX: + break try: # Ensure the prime *can* be circular if prime > 9: @@ -41,7 +41,7 @@ def main(): raise NotCircular() # Check all permutations for rotation in cyclic_rotation(prime): - if rotation not in prime_list: + if not is_prime(rotation): raise NotCircular() circular_primes.append(prime) except NotCircular: