def test_max_prime_overlaps_interval(): # Test when max_prime > N for s, g, mp, expected in ( (1, 99, 2, 50), (1, 99, 3, 34), (1, 99, 5, 28), (1, 99, 7, 25), (1, 99, 11, 25), (1, 99, 100, 25), (1, 99, 200, 25), ): #print (s, g, mp, expected, [s+i for i, v in enumerate(utils.sieve(s, g, mp)) if not v]) assert expected == utils.sieve(s, g, mp).count(False) assert utils.sieve(s, g, mp) == brute(s, g, mp)
def main(): sums = [] prime_sum = 0 primes = [p for p in sieve(LIMIT)] for p in primes: prime_sum += p sums += [prime_sum] maxlen = 0 number = 0 for index, s in enumerate(sums): if s < LIMIT and in_primes(primes, s): maxlen = index number = s for i in range(index - maxlen - 1, -1, -1): sr = s - sums[i] if sr >= LIMIT: break if in_primes(primes, sr): maxlen = index - i number = sr print("Prime =", number, "Longest chain =", maxlen)
def test_limit_limitted(): # Test that limit is decreased to sqrt(s + g) mp = 10 ** 10 for s, g, expected in ( (1, 99, 25), (1000, 1000, 135), (10 ** 6, 100, 6), (10 ** 9, 100, 7), ): composites = utils.sieve(s, g, mp) for i, c in enumerate(composites): assert gmpy2.is_prime(s + i) == (not c) assert expected == composites.count(False)
def test_sieve_primepi(): # Easy to generate these with `primesieve <start> <start + gap> for s, g, mp, expected in ( (0, 100, 10, 25), (1, 99, 10, 25), (1, 99, 100, 25), (101, 100, 20, 21), (101, 100, 100, 21), (1001, 1000, 3, 334), (1001, 1000, 30, 151), (1001, 1000, 50, 135), (1000001, 10000, 1100, 753), ): assert expected == utils.sieve(s, g, mp).count(False)
def test_zero_one_composite(): # Test that 0, 1 are "composite" in our sieve for s, g in ( (0, 10), (1, 5), (0, 1), (0, 2), (1, 1), (1, 2) ): composites = utils.sieve(s, g, 10) if s == 0: assert composites[0] == True if s + g - 1 >= 1: assert composites[1 - s] == True
def loop(absupto): """ We know that b must be prime and a must be odd """ from utils import sieve possbs = sieve(absupto) max_consec = 0 consec_ab = (0,0) for b in possbs: for a in range(-b, absupto, 2): length = len(list(fns(a,b))) if length > max_consec: max_consec = length consec_ab = (a, b) return max_consec, consec_ab
def loop(absupto): """ We know that b must be prime and a must be odd """ from utils import sieve possbs = sieve(absupto) max_consec = 0 consec_ab = (0, 0) for b in possbs: for a in range(-b, absupto, 2): length = len(list(fns(a, b))) if length > max_consec: max_consec = length consec_ab = (a, b) return max_consec, consec_ab
def test_sieve(): for s, g, mp in ( (1, 100, 10), (11, 89, 10), (100, 100, 10), (1001, 100, 10), (1001, 1000, 10), (1001, 100, 50), (1001, 1000, 50), (5, 1000, 3), ): expect = brute(s, g, mp) result = utils.sieve(s, g, mp) assert len(expect) == len(result) #print([1 * v for v in expect]) #print([1 * v for v in result]) #print([s + i for i, v in enumerate(expect) if v]) print([(s+i, a, b) for i, (a, b) in enumerate(zip(expect, result)) if a != b]) assert expect == result, (s, g, mp)
# Pandigital prime # n != 8, 9 from utils import sieve primes = sieve(8000000) def check(n): n = str(n) l = len(n) if "0" in n: return False for i in range(1, l+1): if str(i) not in n: return False return True candidate = [p for p in primes if check(p)] print candidate[-1]
import utils prime_list = utils.sieve(1e6) def check_devided(p): """ """ power_of_power = 9 mod = 10 for i in range(power_of_power): mod = mod**10 % p if mod % p == 1: return True else: return False result = 0 count = 0 for p in prime_list[2:]: #because it not devided by 2 and 3 check = check_devided(p) if check: result += p count += 1 if count == 40: print(result)
# Problem 49 # real 0m0.153s # user 0m0.125s # sys 0m0.015s from utils import sieve from itertools import permutations from utils import is_prime primes = {p for p in sieve(10000) if len(str(p)) == 4} def solve(): for p in primes: # something something permutations digits = [digit for digit in str(p)] nums = [] for perm in permutations(digits): nums.append(''.join(str(d) for d in perm)) # Ok, so now I have all the 4 bit rotated numbers. solution_nums = {int(num) for num in nums if int(num) in primes} if(len(solution_nums) <4): continue for n in solution_nums: if (n-p == 3330 and n+3330 in solution_nums): return(p,n,n+3330) print(solve())
# Problem 35 # real 0m0.818s # user 0m0.769s # sys 0m0.038s from utils import is_prime from utils import sieve primes = [p for p in sieve(1000000)] def is_rotatable(p): for a in range(1,len(p)): if not is_prime(int(p[a:]+p[:a])): return False return True rotatable_primes = [p for p in primes if is_rotatable(str(p))] print(len(rotatable_primes))
# Largest prime factor from utils import sieve from math import sqrt target = 600851475143 primes = sieve(int(target)) p_index = 0 target_factor = [] while True: p = primes[p_index] if target < p: break elif target % p == 0: target /= p target_factor.append(p) else: p_index += 1 print target_factor
#!/usr/bin/env python from utils import sieve size = 2000000 prime = sieve(size) i = 0 sum = 0 while i < size: if prime(i): sum = sum + i i = i + 1 print sum
#!/usr/bin/env python import sys from collections import Counter from utils import sieve P = 47 isprime = sieve(P) primes = [] for i in xrange(P + 1): if isprime[i]: primes.append(i) # it's same as for up to 10^14 # so that's how we know when to stop :) # technically supposed to use: # https://en.wikipedia.org/wiki/St%C3%B8rmer%27s_theorem # to get the bound. # w/e, I'm too busy to know random number theory facts. MAX = 10**13 def printc(c): todelete = [] for k, v in c.iteritems(): if v == 0: todelete.append(k) for k in todelete: del c[k] psmooth = set()
# Truncatable primes from utils import sieve limit = 1000000 primes = sieve(limit) primes_set = set(primes) def check(p): p = str(p) n = len(p) if n == 1: return False for s in range(1, n): if int(p[s:]) not in primes_set: return False if int(p[:s]) not in primes_set: return False return True candidate = [p for p in primes if check(p)] print(sum(candidate))
# -*- coding: utf-8 -*- """ Created on Mon Apr 16 14:55:47 2018 @author: lamwa """ import utils RANGE = 1000000 _, p = utils.sieve(RANGE) n = 1 while True: mod = p[n - 1] * p[n - 1] rem = (utils.power_mod(p[n - 1] - 1, n, mod) + utils.power_mod(p[n - 1] + 1, n, mod)) % mod if rem >= 10**10: break n += 1 print(n)
# Quadratic primes # n2 + an + b # b is prime from utils import sieve primes = sieve(3000000) primes_set = set(primes) def check_prime_chain(a, b): n = 0 while True: k = n**2 + a * n + b if k in primes_set: n += 1 else: break return n max_a, max_b = 0, 0 max_chain = 0 # b = primes < 1000 possible_b = primes[:168] + [-i for i in primes[:168]] for a in range(-1000 + 1, 1000): for b in possible_b: c = check_prime_chain(a, b) if c > max_chain: max_chain = c
def notdecomposeable(odd): return not any(sqrt((odd - pr) / 2.).is_integer() for pr in sieve(odd))
def notdecomposeable(odd): return not any(sqrt((odd - pr)/2.).is_integer() for pr in sieve(odd))
achieve same # of factors in a and b by keeping track of the largest multiplicity possible for each prime for factorizing multiplicities starting from the ith factor of N!. Note that we get the most pruning by considering the factors of N! in decreasing order of multiplicity. Last trick is a counting trick: if a<b and a and b have same number of factors, note that we will double count this case if we do not have some extra bookkeeping. Instead of tracking whether a<b in the dp (which is hard), we track whether a==b in the dp (which is much easier), and if the have the same number of factors in the end, we add 2 to the total instead of 1. Since we have now double-counted all the cases, the final answer is achieved halving. """ N = 100 # we need to factor largest multiplicity of anything <= 100 (+1), which will never exceed 100 itself primes = np.nonzero(sieve(N))[0] factors = Counter() for i in xrange(2, N+1): factors.update(factor(i, primes)) _mem = {} def same_divisor_count(i, div_factor_diff, equal, factorcounts, bounds): # remove 0 entries and do bounds check for k, c in div_factor_diff.items(): if c==0: del div_factor_diff[k] else: if i==len(bounds) or abs(c) > bounds[i][k]: return 0 if i==len(factorcounts): assert len(div_factor_diff) == 0 return 2 if equal else 1
def main(): primes = utils.sieve(10000) composites = set(n for n in range(2, 10000) if n not in primes) twicesquares = set(2*(n**2) for n in range(100)) sums = set(sum(c) for c in product(primes, twicesquares)) print(min(n for n in composites if n not in sums and n % 2 != 0))
from utils import sieve from itertools import permutations, product import re primes = sieve(1000000) primes_set = set(primes) def generate_number(template): a = re.sub("\*", "0", template) b = re.sub("\d*(.*)", "\\1", template) b = re.sub("\d", "0", b) b = re.sub("\*", "1", b) # return a,b a, b = int(a), int(b) number = [a + b * n for n in range(10)] if template[0] == "*": number = number[1:] return number def count_primes(number): np = 0 for n in number: if n in primes_set: np += 1 return np def generate_template(nstar, ndigit): templates = []
samClockCountDict = {} def samClockCount(n): if n in digitPatterns: return 2*len(digitPatterns[n]) elif n not in samClockCountDict: cost = sum(len(digitPatterns[int(digit)]) for digit in str(n)) samClockCountDict[n] = cost*2 + samClockCount(digitalRootStep(n)) return samClockCountDict[n] #maxClockCountDict = {} #def maxClockCount(n): #for n in range(a,b): if __name__ == "__main__": a = 10**7 b = 2 * a _primes = sieve(b) for index in range(len(_primes)): if _primes[index] > a: _primes = _primes[index:] break print(_primes) for p in _primes: print(p,samClockCount(p))
#!/usr/bin/env python import utils MAX = 100 + 1 prime = utils.sieve(MAX) def prime_factors(n): factors = [] while not prime(n): for i in range(n): if prime(i) and n % i == 0: factors.append(i) n = n / i break factors.append(n) return factors # prime factor each a/b factors = [[], []] for i in range(2, MAX): factors.append(prime_factors(i)) def encode(factors, exponent): factors = factors[:] encoded = "" while factors: expsum = exponent base = factors.pop(0)
#!/usr/bin/env python import utils prime = utils.sieve(1200000) quad = lambda a, b, n: (n**2) + (a*n) + b def consec_primes(a, b): n = 0 while True: if prime(quad(a, b, n)): n = n + 1 else: return n largest = (1, 1, 1) for a in xrange(-1000, 1000): for b in xrange(-1000, 1000): if b % 2 == 0 or\ b % 3 == 0 or\ b % 5 == 0: pass else: prime_count = consec_primes(a, b) if prime_count > largest[2]: largest = (a, b, prime_count) print largest[0] * largest[1]
""" Project Euler Problem 10 ======================== The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. """ from utils import sieve MAX = 2000000 print sum(sieve(MAX))
#Problem 50 # real 0m1.834s # user 0m1.765s # sys 0m0.042s from utils import sieve from utils import is_prime primes = sieve(1000000) max_primes = 1 for x in range(78498-50): for y in range(499,600): total = sum(primes[x+z] for z in range(y)) if total in primes and y > max_primes: print(y,total) max_primes = y print(max_primes)
# -*- coding: utf-8 -*- """ Created on Sun Apr 15 11:26:43 2018 @author: lamwa """ import utils RANGE = 100 TH = 4000000 _, p_list = utils.sieve(RANGE) ans = 1e20 def dfs(n, i, cur, r): global ans if n >= ans: return None if (cur + 1) // 2 > TH: ans = n return None for t in range(1, r + 1): n *= p_list[i] dfs(n, i + 1, cur * (2 * t + 1), t) dfs(1, 0, 1, 100)
from utils import sieve from math import sqrt l = sieve(100000) def f(): n = 1 while (1>0): for x in l: if (x >=n): break; print n,x a = sqrt((n-x)%2) if a == int(a): continue else: return n n +=2 def g(): for x in xrange(10,20): for y in l: if y >= x: break print x,y,x-y print f()
# Problem 10 # real 0m0.389s # user 0m0.318s # sys 0m0.062s from utils import sieve print(sum(sieve(2000000)))
from utils import sieve from math import log, sqrt import time N = 10000000 primes = sieve(N / 2) def M(p1, p2, N): N1 = int(log(N, p1)) N2 = int(log(N, p2)) candidate = [ p1**i * p2**j for i in range(1, N1 + 1) for j in range(1, N2 + 1) ] max_candidate = 0 for c in candidate: if c <= N and c > max_candidate: max_candidate = c return max_candidate start = time.time() sum_M = 0 max_i = sqrt(N) for i in primes: if i <= max_i: max_j = N / i for j in primes: if j <= max_j and j > i: m = M(i, j, N) sum_M += m
#!/usr/bin/env python import tqdm from utils import c, sieve """ Idea: write S(L) as a summation, sum over terms with same power of 5. Tricky part is computing the coefficient; for this we can use identity sum(c(n,i) for i in xrange(k+1)) == c(n+1,k+1) """ N = 50*10**6 prime = sieve(N) pi = [0]*(N+1) for i in xrange(2,N+1): pi[i] = pi[i-1] + prime[i] def check(n): ret = 0 for k in xrange(pi[n]+1): ret += 6*c(n-1,k)*5**(n-1-k) return ret mod = 10**9+7 ans=0 stop = 0 for diff in tqdm.tqdm(xrange(1, N+1)): while stop<N and stop+1-pi[stop+1]<=diff: stop += 1
# 10001st prime # pn ~ n/log(n) # 200000./log(200000) = 16385 from utils import sieve from math import log n = 200000 primes = sieve(n) print len(primes) print primes[10000]
import utils RANGE = 20000 def A(n): x = 1 k = 1 while x > 0: x = (x * 10 + 1) % n k += 1 return k is_p, _ = utils.sieve(RANGE) ans = 0 n = 3 cnt = 0 while True: if not is_p[n]: if (n - 1) % A(n) == 0: ans += n cnt += 1 if cnt == 25: break n += 2 if n % 5 == 0: n += 2
# Problem 3 # real 0m0.192s # user 0m0.153s # sys 0m0.029s from utils import sieve import math target = 600851475143 primes = sieve(int(math.sqrt(target))) print(max(p for p in primes if not target%p))
from utils import sieve, permuta, lintstr from math import sqrt l = sieve(int(sqrt(7654321))) a = permuta("7654321") a.reverse() def check(x): for y in l: if x%y == 0: return 0 return 1 def f(): for x in a: if check(int(x))==1: return x return 0 print f()
# Problem 87 #real 0m2.592s #user 0m2.489s #sys 0m0.071s from utils import sieve target = 50000000 quads = sieve(int(target ** (1/4))) triples = sieve(int(target ** (1/3))) doubles = sieve(int(target ** (1/2))) vals = set() for q in quads: for t in triples: for d in doubles: s = d**2 + t**3 + q**4 if s < target: vals.add(s) print(len(vals))