def main(): """main function""" primes_r = p.primes(10) # 1 digit primes. primes_l = p.primes(10) # 1 digit_primes. answer = [] while True: tmp = filter(func_prime, combination_nums(primes_l, primes_r)) tmp.sort() answer.extend(list(set(tmp))) if len(answer) >= TOTAL_NUMS: # break out while loop. break primes_r = next_right(primes_r) primes_l = next_left(primes_l) print sum(answer[:TOTAL_NUMS]) # print sum of first eleven
def main(): """main function""" primes_r = p.primes(10) # 1 digit primes. primes_l = p.primes(10) # 1 digit_primes. answer = [] while True: tmp = filter(func_prime, combination_nums(primes_l, primes_r)) tmp.sort() answer.extend(list(set(tmp))) if len(answer) >= TOTAL_NUMS: # break out while loop. break; primes_r = next_right(primes_r) primes_l = next_left(primes_l) print sum(answer[:TOTAL_NUMS]) # print sum of first eleven
def solve_by_pairing(target_size=target_set_size): # This algorithm will populate prime_pairs with each prime (key) pointing to a set of all # smaller primes that form a valid prime pair with it. # Each of these is then checked by get_connected_set to see if there are enough pairwise # connections to complete the problem. # NOTE: prime index starts from 3 to avoid primes 2 and 5, which cannot be part of any prime pair. # 3 is chained into the inner loop, but not the outer loop because no valid primes are less than 3. log_step = 1000 next_step = 0 for p in primes(step=10000, start_index=3): for q in chain(reversed(sieve_primes(max_prime=p)[3:-1]), [3]): populate_prime_pairs(p, q) if p > next_step: split_timer() print(f"Reached p > {next_step} -- {p}: {prime_pairs.get(p)}") next_step += log_step if p in prime_pairs: p_set = get_connected_set(prime_pairs[p], target_size - 1) if p_set: p_set.add(p) return sorted(p_set)[:target_size]
def sum_to_p(p, limit=limit): """ Return a 2-tuple containing the largest possible prime that is a sum of consecutive primes ending in p, and the number of terms in the sum. """ res = (p, 1) total = p # This generator will ensure that we are always list primes smallest to largest, starting 1 below p for i, q in enumerate(filter(lambda x: x < p, primes(reverse=True, step=p)), start=2): total += q if total > limit: return res elif is_prime(total): res = (total, i) if q == 2: return res return res
def prime_no_ff(no): from prime import primes g = primes() p = 0 for i in xrange(1,no+1): p = g.next() if i == no: return p
def prime_factors_of(n): for p in primes(n): (a, b) = divmod(n, p) while b == 0: yield p n = a (a, b) = divmod(n, p) if n == 1: break
def test_primes(clear_prime_cache): for step_size in range(3, 15): generated = list() for i, p in enumerate(prime.primes(step=step_size)): if i >= 100: break generated.append(p) assert generated == primes, "Failed prime generator. (:step_size:={})".format(step_size)
def primePowerTriples(M): s1 = bitset.makebitset(M, 0) count = 0 for a in prime.primes(): if a**2 >= M: break for b in prime.primes(): if a**2 + b**3 >= M: break for c in prime.primes(): n = a**2 + b**3 + c**4 if n >= M: break elif bitset.getbit(s1, n) == 0: count += 1 bitset.setbit(s1, n) return count
def main(): """main function""" primes_4digits = filter(is4digit, primes(10000)) ars = found_3arithmetic(primes_4digits) # found unknonw triples. for ar in ars: if ar[0] != 1487: print reduce(lambda a,b:a+b, map(str, ar)) break; # out to loop
def eightPrimeFamilies(): for p in primes(): pstr = str(p) if '0' in pstr[:-1]: d = 0 elif '1' in pstr[:-1]: d = 1 elif '2' in pstr[:-1]: d = 2 else: continue family = list(primeDigitReplacements(pstr, d)) if len(family) == 8: yield (p, family)
def test_primes_start_index(clear_prime_cache): step_size = 14 for start_index in range(30): generated = list() for i, p in enumerate(prime.primes(start_index=start_index, step=step_size)): if i >= 100 - start_index: break generated.append(p) assert generated == primes[start_index:], "Failed prime generator with start_index {}. (:step_size:={})".format(start_index, step_size)
def consecutiveSumPrimes(maxPrime): ps = list(takewhile(lambda x: x < maxPrime, primes())) for i in range(0, len(ps)): total = ps[i] for j in range(i+1, len(ps)): total += ps[j] if total > maxPrime: break if isPrime(total): count = j - i + 1 yield (total, count)
def test_primes_reverse(clear_prime_cache): for step_size in range(3, 15): generated = list() for i, p in enumerate(prime.primes(step=step_size, reverse=True)): if i >= 110: # NOTE: This test must retrieve a extra results since the iteration is not in numerical order. # Since the largest step_size is only 15 we just retrieve a few and then slice them out. break generated.append(p) assert sorted(generated)[:100] == primes, "Failed prime generator with :reverse:=True. (:step_size:={})".format(step_size)
def primeFactors(n): """Use trial division of primes to find factors""" if n in primeFactorMemoized: return primeFactorMemoized[n].copy() for p in prime.primes(): if (n % p == 0): result = primeFactors(n // p) result[p] = result[p] + 1 primeFactorMemoized[n] = result return result.copy()
def numSumsDigitsMax(value, numTerms, maxTerm): # single term if numTerms == 1: return 1 if prime.isPrime(value) and value <= maxTerm else 0 # all 2's if value == numTerms*2: return 1 # split into first term + remaining terms # max term in recursive call cannot be greater than first term maxFirstTerm = min(maxTerm, value - 2 * (numTerms - 1)) primes = prime.primes(maxFirstTerm + 1) return sum(numSumsDigitsMax(value - firstTerm, numTerms - 1, firstTerm) for firstTerm in primes)
def is_pass(n, remove_prime_first=False): """Return True if n passes the criteria for the given conjecture.""" if remove_prime_first: for p in primes(): if p > n: return False elif sqrt((n - p) / 2).is_integer(): return True else: for i in range(1, n // 2): if is_prime(n - 2 * i**2): return True
def test_main(self): print("Fibonacci") for i in range(10): print("{}: {}".format(i, fib(i))) print("Geometric numbers (square, triangle, cube)") for i in range(10): print("{}: {} {} {}".format(i, square(i), triangle(i), cube(i))) print("Primes") prime_list = primes(1000) for p in prime_list[-10:]: print(p) print("Is 999981 prime? {}".format(is_prime(999981))) print("Is 999983 prime? {}".format(is_prime(999983)))
def main(): """main function""" prs = primes(NUM_MAX) # prs is primes below NUM_MAX length = len(prs) # length of prs max_consecutive = 0 max_prime = -1 for i in range(length): for j in range(max_consecutive, length - i + 1): cnum = sum(prs[i:i + j]) # consecutive number if cnum >= NUM_MAX: # if sum is over target value, break j loop break if search(sum(prs[i:i + j]), prs, 1, length - 1): max_consecutive = j max_prime = sum(prs[i:i + j]) print max_prime
def main(): """main function""" prs = primes(NUM_MAX) # prs is primes below NUM_MAX length = len(prs) # length of prs max_consecutive = 0 max_prime = -1 for i in range(length): for j in range(max_consecutive, length-i+1): cnum = sum(prs[i:i+j]) # consecutive number if cnum >= NUM_MAX: # if sum is over target value, break j loop break if search(sum(prs[i:i+j]), prs, 1, length-1): max_consecutive = j max_prime = sum(prs[i:i+j]) print max_prime
def dynamic_solution(limit=limit): """Keeps a running total of sums of primes and returns value of longest sum that is prime and less than limit.""" start_time = time() # Accumlate attributes for sums starting from each prime in prime_sums. # Indexed by the position of the starting prime, attributes of prime_sums will be like: # (start, total, best, length), where `start` is this tuple's index (for convenience), # `total` is the running sum, `best` is the last total which was prime, and `length` # is the length of the best sum starting from this prime prime_sums = [] best_run = 1 # Just keep track of the length for optimizing stopping condition def update_sum(i, p, total, best, start, length, limit=limit): total += p if total > limit: return (None, best, start, length ) # Indicates this sum can stop accumulating elif is_prime(total): best = total length = i - start + 1 return (total, best, start, length) for i, p in enumerate(primes()): for j, tally in enumerate(prime_sums): # Updating a cummulative total if tally[0]: prime_sums[j] = update_sum(i, p, *tally) if tally[3] > best_run: best_run = tally[3] elif tally[3] < best_run: # This sum is no longer relevant, so we can remove it del prime_sums[j] # Create an entry for the current prime's cummulative total if p <= limit / best_run: prime_sums.append((p, p, i, i)) # Check if we can stop (if all totals have exceeded the limit) elif not any(x[0] for x in prime_sums): res = sorted(prime_sums, key=itemgetter(3))[-1][1:] print("Best sum under {}: total={} ({} terms)".format( limit, res[0], res[2])) print("Execution time: {}".format(time() - start_time)) return res[0]
def slow_solution(): """For each prime, p (starting from 2), finds the longest valid sum ending in p and returns the longest of these over all primes.""" def sum_to_p(p, limit=limit): """ Return a 2-tuple containing the largest possible prime that is a sum of consecutive primes ending in p, and the number of terms in the sum. """ res = (p, 1) total = p # This generator will ensure that we are always list primes smallest to largest, starting 1 below p for i, q in enumerate(filter(lambda x: x < p, primes(reverse=True, step=p)), start=2): total += q if total > limit: return res elif is_prime(total): res = (total, i) if q == 2: return res return res start_time = time() best = ( 2, 1, 2 ) # The sum, the number of terms in the sum, and the last prime in the sum for p in takewhile(lambda x: x <= limit, primes(start_index=2)): curr = sum_to_p(p) # Compare current best to the length of the longest sum ending in p if curr[1] > best[1]: best = (*curr, p) print("Best sum under {}: total={} ({} terms, ending in {})".format( limit, *best)) print("Execution time: {}".format(time() - start_time)) return best[0]
def test_big_number(self): self.assertEqual(primes(5000), [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,\ 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167,\ 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277,\ 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401,\ 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523,\ 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653,\ 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797,\ 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937,\ 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051,\ 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181,\ 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297,\ 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439,\ 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549,\ 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657,\ 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783,\ 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907,\ 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029,\ 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143,\ 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287,\ 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393,\ 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543,\ 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677,\ 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777,\ 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897,\ 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023,\ 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169,\ 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301,\ 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407,\ 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533,\ 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637,\ 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761,\ 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877,\ 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001,\ 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099,\ 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229,\ 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339,\ 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463,\ 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591,\ 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703,\ 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817,\ 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957,\ 4967, 4969, 4973, 4987, 4993, 4999])
def test_not_even(self): self.assertNotEqual( prime.primes(10), [2, 4, 6, 8 ]) # To ensure that output is not a series of even numbers.
def sumOfPrimeFactors(n): return sum(p for p in prime.primes(n + 1) if n%p == 0)
Find the value of n ≤ 1,000,000 for which n/φ(n) is a maximum. ''' prime.loadPrimes('primes.bin') def product(it): result = next(it) for x in it: result *= x return result def phi(n): factors = factorization.primeFactors(n).keys() result = round(n * product(1 - (1/p) for p in factors)) return result assert(phi(2) == 1) assert(phi(3) == 2) assert(phi(4) == 2) assert(phi(10) == 4) # create the number less than 1000000 with most prime factors # This will be co-prime to the least number of other values, maximizing n / phi(n) n = 1 for p in prime.primes(): if n * p > 1000000: break n *= p print(n, phi(n), n / phi(n))
import math import prime ps = prime.primes(100) print ps a=1 c=0 step=31 for x in ps: a*=x b=math.log(a)/math.log(2) cl=c c=int(b) if( cl<step and c >=step ): print "x=%d b=%f" % (x,b) step+=32 c = [23,47,61] a=1 for x in ps: a*=x if x in c: b=math.log(a)/math.log(2) print "x=%d a=%d b=%f" % (x,a,b) a=1
Circular primes Problem 35 The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? """ def rotations(n): ns = str(n) nd = len(ns) ns = ns * 2 for i in range(0, nd): yield int(ns[i:i+nd]) assert(list(rotations(197)) == [197, 971, 719]) def isCircularPrime(i): for j in rotations(i): if not prime.isPrime(j): return False return True assert(isCircularPrime(197)) circularPrimes = [p for p in prime.primes(1000000) if isCircularPrime(p)] print(len(circularPrimes))
def test_one_prime(self): # To ensure that the output does not include 1. self.assertNotIn(1, prime.primes(10))
Problem 27 Euler discovered the remarkable quadratic formula: n² + n + 41 It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 41² + 41 + 41 is clearly divisible by 41. The incredible formula n² − 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The product of the coefficients, −79 and 1601, is −126479. Considering quadratics of the form: n² + an + b, where |a| < 1000 and |b| < 1000 where |n| is the modulus/absolute value of n e.g. |11| = 11 and |−4| = 4 Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0. """ def consecutivePrimes(a): for n in count(0): y = n*n + a[0]*n + a[1] if not isPrime(y): return n assert(40 == consecutivePrimes((1, 41))) primesTo1000 = list(takewhile(lambda x: x < 1000, primes())) coefficients = ((a,b) for b in primesTo1000 for a in range(-b, 1000, 2)) # assumes b is not 2 in solution a, b = max(coefficients, key=consecutivePrimes) print((a,b),'generates', consecutivePrimes((a,b)), 'primes', 'product = ', a*b)
from collections import deque from prime import primes from rotations import rotations maxn = 1000000 total = 0 checked = [] circ = [] primelist = primes(maxn) for m in primelist: if m in checked: continue rots = rotations(m) if set(rots) < set(primelist): circ += list(set(rots) - set(circ)) checked.extend(rots) print circ print len(circ)
def test_zero_prime(self): # To ensure that the output does not include 0. self.assertNotIn(0, prime.primes(10))
def test_output_prime(self): # To test if output is prime. self.assertEqual(prime.primes(5), [2, 3])
def test_not_odd(self): self.assertNotEqual( prime.primes(10), [3, 5, 7, 9]) # To ensure output is not a series of odd numbers.
from prime import primes primelist = primes(10000) print len(primelist) length, ag, bg = 0, 0, 0 for a in range(1000): for b in range(1001): pplist, nplist, pnlist, nnlist = [], [], [], [] n = 0 while 1: ppprime = (n**2) + (a * n) + b if ppprime not in primelist: break pplist.append(ppprime) n += 1 n = 0 while 1: npprime = (n**2) + (-a * n) + b if npprime not in primelist: break nplist.append(npprime) n += 1 n = 0 while 1: pnprime = (n**2) + (a * n) - b if pnprime not in primelist: break pnlist.append(pnprime) n += 1
1/6 = 0.1(6) 1/7 = 0.(142857) 1/8 = 0.125 1/9 = 0.(1) 1/10 = 0.1 Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle. Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part. """ def geometricSeries(a, r): sum = 0 while True: sum += a yield sum a *= r def nines(): return geometricSeries(a=9, r=10) def digitCycle(p): for i, n in zip(range(1,p), nines()): if n % p == 0: return i return 0 primesTo1000 = takewhile(lambda x: x < 1000, primes()) result = max(primesTo1000, key=digitCycle) print('1/%d has digit cycle length %d' % (result,digitCycle(result)))
def test_requires_integer_as_argument(self): with self.assertRaises(Exception) as context: primes("23") self.assertEqual("Only integers expected as arguments", str(context.exception))
def p3(number): for p in reversed(primes(10000)): if p*p > number: break if number % p == 0: return p
def test_returns_prime_numbers_less_or_equal_to_n(self): self.assertLessEqual(max(primes(13)), 13)
def test_returns_prime_numbers(self): self.assertListEqual([2, 3, 5, 7, 11, 13], primes(13)) self.assertListEqual([2, 3, 5, 7, 11, 13, 17], primes(17)) self.assertListEqual([2, 3, 5, 7, 11, 13, 17], primes(18))
def test_returns_empty_list_when_n_is_less_than_2(self): self.assertEqual([], primes(1)) self.assertEqual([], primes(-1))
def firstFactor(n): for p in prime.primes(): if n % p == 0: return p
def test_returns_list_with_two_when_n_is_two(self): self.assertEqual([2], primes(2))
return is_prime(r_trunc) and r_truncatable(r_trunc) def l_truncatable(p): """Return True if all left-side truncations of p are prime (does not test p itself).""" if p < 10: return is_prime(p) else: l_trunc = int(str(p)[1:]) return is_prime(l_trunc) and l_truncatable(l_trunc) def truncatable(p): """Return True if all left- and right-side truncations of p are prime (does not test p itself).""" return r_truncatable(p) and l_truncatable(p) for p in primes(): if p < 10: continue if truncatable(p): trunc_set.add(p) trunc_count += 1 print(p) if trunc_count >= limit: break print("Truncatable primes: {}\nSum: {}".format(sorted(trunc_set), sum(trunc_set))) print("Execution time: {}".format(time.time() - start_time))
def primes_four(): """Return generator of 4-digit primes, largest first.""" return takewhile(lambda x: x > 1000, primes(reverse=True, step=10000))
def p10(): return sum(primes(200000))
def test_not_float(self): # To ensure float types raise a ValueError. with self.assertRaises(TypeError): prime.primes(2.0)
def p7(): return primes(150000)[10000]
def test_one(self): # To ensure that the output for one is an empty list. self.assertEqual(prime.primes(1), [])
import prime p = prime.primes(999000) p10000 = {x for x in p if x < 10000} amax = 0 bmax = 0 pnum = 0 for b in p10000 : for a in range(-9999,10000) : n = 0 while n**2 + a*n + b in p : n += 1 if n > pnum : amax, bmax, pnum = a, b, n print("n =", 71, " a =", amax, " b =", bmax, ". a*b =", amax*bmax)
from __future__ import division from prime import prime, primes import sys def rec(currents, ps): if len(currents) == 5: print(currents, sum(i for i in currents)) sys.exit(0) for p in ps: if p <= currents[-1]: continue for c in currents: if not prime(int(str(c) + str(p))) or \ not prime(int(str(p) + str(c))): break else: rec(currents + [p], ps) x = 5000 while True: ps = primes(x) for p in ps: rec([p], ps) x += 1000