# The intended value has to be in the primes list, meaning < limit. # The biggest possible sequence will involve the smallest primes that add up # to limit. def get_max_sequence(): seq = 0 s = 0 while (s < limit): s += primes_list[seq] seq += 1 return seq limit = 1000000 # Generate list of primes. soa = SieveOfAtkin(limit) primes = set(soa.getPrimes()) # Because result is given as a set, turn into a list and sort it. primes_list = list(primes) primes_list.sort() # We know that the sequence will have a maximum: # - only consider sequences of that size or smaller for l in xrange(get_max_sequence(), 1, -1): i = 0 value = sum(primes_list[i:i + l]) # Because the value has to be in primes_list, no need to check values bigger # than the limit. while value < limit: if value in primes: print l, value exit(0)
def main(): primes_sieve = SieveOfAtkin(100000) return primes_sieve.get_nth_prime(10001)
from sieve_of_atkin import SieveOfAtkin from math import sqrt, pow soa = SieveOfAtkin(1000) primes = soa.getPrimes() nmax = 0 # Taken from here: http://blog.dreamshire.com/2009/03/26/94/ def is_prime(n): if n == 2 or n == 3: return True if n < 2 or n % 2 == 0: return False if n < 9: return True if n % 3 == 0: return False r = int(sqrt(n)) f = 5 while f <= r: if n % f == 0: return False if n % (f + 2) == 0: return False f += 6 return True # b has to be prime, so that when n = 0 the result is prime for a, b in [(a, b) for a in range(-1000, 1000) for b in primes]: n = 1 while is_prime(pow(n, 2) + a * n + b): n += 1 if n > nmax: nmax, product = n, a * b
def testIsPrime(self): soa = SieveOfAtkin(100) self.assertFalse(soa.isPrime(2)) soa.flip(2) self.assertTrue(soa.isPrime(2))
# We don't need the actual factorization, only the number of factors def distinct_prime_factors(number): distinct_prime_factors = 0 for p in primes: if number % p == 0: distinct_prime_factors += 1 number /= p return distinct_prime_factors number_of_distinc_primes = 0 number = 2 # For this specfic of the problem, we only need primes up to 700. # To a more generic number factorization, we would need primes up to number/2. soa = SieveOfAtkin(700) primes = set(soa.getPrimes()) while number_of_distinc_primes != 4: # If number of distinct primes is 4, count it if distinct_prime_factors(number) == 4: number_of_distinc_primes += 1 # If not, reset to 0 else: number_of_distinc_primes = 0 number += 1 print "The first number is:", number - 4
from sieve_of_atkin import SieveOfAtkin soa = SieveOfAtkin(800000) primes = set(soa.getPrimes()) def truncableRight(val): s = str(val) for i in range(len(s), 0, -1): if int(s[:i]) not in primes: return False return True def truncableLeft(val): s = str(val) for i in range(len(s)): if int(s[i:]) not in primes: return False return True result = 0 for i in (i for i in primes if i > 7): if truncableRight(i) and truncableLeft(i): result += i print result