def pollard_p_minus_one(n, b=5, m=13, a=2): if b < 1: raise Exception('B must be bigger than 1') if b >= m: raise Exception('B must be less than sqrt(n)') if m >= b**2: raise Exception('M must be less than B^2') if m >= math.sqrt(n): raise Exception('M must be less than sqrt(n)') if a < 1: raise Exception('a must be bigger than 1') mb_primes = utils.primes(2, b) primes_mul = reduce(operator.mul, mb_primes, 1) b = (a**primes_mul) % n q = utils.gcd(b - 1, n) if q > 1: return q, n // q m_primes = utils.primes(b, m) for m in m_primes: fm = (b**(m - 1)) % n gm = utils.gcd(fm, n) if gm > 1: return gm, n // gm return math.nan, math.nan
def main(): number = 600851475143 sqrt = int(math.sqrt(number)) for prime in reversed(primes(sqrt)): if number % prime == 0: return prime
def getFraction(self): n = 1 d = 1 for (p, a) in zip(utils.primes(), self): if a > 0: n *= p**a elif a < 0: d *= p**(-a) return (n, d)
def most_consecutive_primes(n): # given n^2 + ax + b, assume the highest result we can get is 2n^2 + n # generate all primes up to that _primes = utils.primes(2*pow(n, 2) + n) primes = {} for p in _primes: primes[p] = True a, b = 0, 0 ps = 0 for _a in range(n): for _b in range(n): # consider all combos of positive/negative for __a, __b in [(_a, _b), (-_a, _b), (-_a, -_b), (_a, -_b)]: # create the function def f(x): return pow(x, 2) + __a*x + __b # look for primes x = 0 _ps = -1 while primes.get(f(x)): _ps += 1 x += 1 if _ps > ps: a, b = __a, __b ps = _ps return a*b
def main(): result = 0 while True: result += 1 x = ways(take_upto(result, primes()), result) if x > 5000: break return result
def getEpimoricZip(r): "(6/5) -> [(3/2,1), (5/4,-1)]" result = [] while r != Rational(1): p, i = zip(utils.primes(), r)[-1] e = Rational(p, p-1) result.insert(0, (e, i)) r /= e ** i return result
def testRandom3Digit(): nsamples = 10 for i in range(nsamples): threeDigitPrimes = primes(1000)[2:] random.shuffle(threeDigitPrimes) p1, p2 = threeDigitPrimes[0], threeDigitPrimes[1] n = p1 * p2 print("primes: " + str(p1) + ", " + str(p2)) print(quadSieve(n)) assert (quadSieve(n) == {p1, p2})
def longest_recurring_cycle(n): for denom in utils.primes(n)[::-1]: period_length = 1 # 1 % denom is always 1, so when it's seen again we know the period is over while pow(10, period, denom) != 1: period_length += 1 # reptend prime check if denom - 1 == period_length: return denom
def main(): trunc_count = 11 trunc_primes = [] for p in take_from(10, primes()): if truncatable_prime(p): trunc_count -= 1 trunc_primes.append(p) if trunc_count == 0: break return sum(trunc_primes)
def compute(): PRIMES = primes(1000) target = 10 # we are given that 10 only has 5 prime partitions while True: prime_partitions = [0] * (target + 1) prime_partitions[0] = 1 for p in PRIMES: for j in range(p, target + 1): prime_partitions[j] += prime_partitions[j - p] if prime_partitions[target] > 5000: break target += 1 return target
def compute(): # We are given that this pattern holds at least until 33 # We will cheat a bit here and assume that this pattern will not hold until 10,000 # This can be found with some experimentation prime_list_full = primes(10000) num = 35 while True: prime_list = [p for p in prime_list_full if p < num] if not (any( sqrt(num / 2 - p / 2) == int(sqrt(num / 2 - p / 2)) for p in prime_list)) and not is_prime(num): return num num += 2
def main(): prime_numbers = utils.primes(10000) odd_composites = [n for n in range(2, 10000) if (utils.isprime(n) == False) & (n % 2 != 0)] for odd_composite in odd_composites: number_found = False for prime in prime_numbers: difference = odd_composite - prime if difference > 0: if np.sqrt(difference / 2) == int(np.sqrt(difference/2)): number_found = True if number_found == False: return odd_composite
def compute(): LIMIT = 50_000_000 max_prime = int(sqrt(LIMIT)) # prime**2 must be less than LIMIT PRIMES = primes(max_prime) numbers = set() for x in PRIMES: for y in PRIMES: for z in PRIMES: value = x**2 + y**3 + z**4 if value < LIMIT: numbers.add(value) else: break return len(numbers)
def factor_map(max): m = {} primes = utils.primes(max) sprimes = set(primes) for n in xrange(1, max): if n in sprimes: m[n] = set() continue factors = [] for p in primes: if p < n and n % p == 0: factors.append(p) m[n] = set(factors) return m
def run(): to_proc = [] for prime in primes(1000,10000): to_proc.append(prime) to_proc.sort() permutations = [] for i in to_proc[:]: if len(permutations) == 2: break for j in xrange(1, (10000-i)/2): second = str(i+j) if is_prime(i+j) and is_permutation(str(i), second): third = i+j+j if is_prime(third) and is_permutation(second, str(third)): permutations.append((i,i+j,i+j+j)) print permutations
def main(): primes_less_1000 = list(takewhile(lambda x: x < 1000, primes())) highest = [0, 0, 0] for a in range(-999, 1001): for b in primes_less_1000: n = 0 while is_prime((n**2) + (a*n) + b): n += 1 if n > highest[0]: highest[0] = n highest[1] = a highest[2] = b print(highest) return highest[1] * highest[2]
def main(): total = 0 primes_less_limit = take_upto(MILL, primes()) for p in primes_less_limit: n = p circular = True for _ in str(n): if not is_prime(n): circular = False break n = rotate_digits(n) if circular: total += 1 return total
def main(): length = 6 primes = [str(prime) for prime in utils.primes(10 ** length) if 10 ** (length - 1) < prime < 10 ** length] counter = Counter() for prime in primes: digit_counter = Counter(prime) for d, digit_count in digit_counter.iteritems(): if digit_count == 1: continue indices = [i for i, x in enumerate(prime) if x == d] for length in xrange(2, digit_count + 1): for i in itertools.combinations(indices, length): counter.update([tuple([digit if digit_index not in i else -1 for digit_index, digit in enumerate(prime)])]) result = counter.most_common(1)[0][0] for prime in primes: if is_match(result, prime): print prime break
def factor(num, b): """ factor using Pollard's p-1 method num: odd number to factor b: smoothness cap """ primeList = utils.primes(b) m = 1 for prime in primeList: exp = math.floor(math.log(b, prime)) m *= pow(prime, exp) a = 2 g = utils.xgcd(pow(a, m, num) - 1, num)[0] if (1 < g and g < num): return g elif (g == 1): # Increase B return -1 elif (g == num): # Decrease B return -2
import utils from itertools import combinations, takewhile, product, chain primesSet = list(map(str, utils.primes(100000000))) primes = list(takewhile(lambda x: int(x) < 10000, list(primesSet))) primesSet = set(primesSet) print len(primes), len(primesSet) def checkAllPrimes(x): if not len(set(x)) == len(x): return False for y, z in combinations(x, 2): if not (y + z in primes and z + y in primes): return False return True def checkAllPrimes2(x1, x2): for y in x1: if not (y + x2 in primes and x2 + y in primes): return False return True # pairs = None # print "Got primes" # pairs = list(filter(checkAllPrimes,
from utils import primes v = 600851475143 lim = v**.5 last = 1 for i in primes(): if v % i == 0: last = i if i > lim: break print(last)
from utils import primes limit = 100 ps = primes(limit) count = [[0 for _ in ps] for _ in range(limit+1)] for n in range(1, limit+1): for i, p in enumerate(ps): if p == n: count[n][i] += 1 count[n][i] += count[n-p][i] if i > 0: count[n][i] += count[n][i-1] for n, cs in enumerate(count): if cs[-1] > 5000: print n break
r = pow(n, (q + 1) / 2, p) while t != 1: i = find_sq_num(t, p) if i >= m: return b = pow(c, 2 ** (m - i - 1), p) m = i c = b * b % p t = t * b * b % p r = r * b % p yield r yield p - r limit = 5 * 10 ** 7 ps = list(primes(int(2 ** 0.5 * limit))) els = array.array('B', '1' * (limit + 1)) for p in ps[1:]: for r in calculate_r(p): init = r if 2 * r * r - 1 != p else r + p for k in xrange(init, limit+1, p): els[k] = 0 count = 0 for i in xrange(2, limit + 1): if els[i]: count += 1 print count
from utils import primes from math import log def powers(l, limit): res = l while res <= limit: yield res res *= l limit = 10**7 ps = list(primes(limit / 2)) res = 0 for lp in ps[::-1]: for s in ps: if lp * s > limit: break if s >= lp: break ans = 0 for l in powers(lp, limit): if l * s > limit: break ans = max(ans, l * list(powers(s, limit / l))[-1]) res += ans print res
from utils import primes, modinv limit = 1000000 ps = list(primes(limit + 100))[2:] res = 0 for p1, p2 in zip(ps, ps[1:]): if p1 > limit: break power10 = 10 ** len(str(p1)) res += ((p2 - p1) * modinv(power10, p2) % p2) * power10 + p1 print res
from utils import primes ty = 100 limit = 10**9 ps = list(primes(ty)) ns = [1] res = set() while ns: n = ns.pop() if n in res: continue res.add(n) for p in ps: x = n * p if x <= limit: ns.append(x) print len(res)
import utils import itertools import time start = time.time() BOUND = 1000000 current = (0,1) primes = list(utils.primes(BOUND)) prime_arr = [False] * BOUND for p in primes: prime_arr[p] = True print ("Primes generated") max_length = 0 for i in range(0, len(primes)): s = 0 curr_length = 0 for p in primes[i:]: s += p if s >= BOUND: break curr_length += 1 if prime_arr[s]: if curr_length > max_length: max_length = curr_length print "New max: %s" % max_length print sum(primes[i:i+curr_length]) print (time.time() - start)
import utils from collections import Counter from itertools import tee, izip def window(iterable, size): iters = tee(iterable, size) for i in xrange(1, size): for each in iters[i:]: next(each, None) return izip(*iters) MAX = 1000000 primes = utils.primes(MAX) def factor_consequtive(x): factors = utils.factor(x, primes) counts = Counter(factors) for k in counts: yield k ** counts[k] def generate_consequtive(): i = 1 while True: yield set(factor_consequtive(i)) i += 1 for a, b, c, d in window(generate_consequtive(), 4): if len(a.union(b).union(c).union(d)) == 16: print a break
def coprimes(*numbers): for p in utils.primes(): if all(n % p == 0 for n in numbers): return False if all(n / p == 0 for n in numbers): return True # stop searching
prime. Answer: """ from __future__ import print_function from utils import timer, primes, take_n, is_prime import itertools ANSWER = None def test_answer(): if ANSWER is None: assert 0, 'Not Completed' else: assert ANSWER == main() PRIMES = list(take_n(10000, primes())) PRIMES_SET = frozenset(PRIMES) @timer def main(): pass if __name__ == '__main__': print(main())
from __future__ import print_function from utils import timer, primes import itertools ANSWER = 65537 def test_answer(): if ANSWER is None: assert 0, 'Not Completed' else: assert ANSWER == main() primes_l = set(itertools.islice(primes(), 10000)) square_sums = [2*(x**2) for x in range(40)] @timer def main(): for n in itertools.count(3, 2): for p in primes_l: if p > n: break for s in square_sums: t = p + s if t == n: break else: return n
from utils import primes, memoize primes = primes(10000000) primeSet = set(primes) @memoize def factors(x): if x in primeSet: return {x} t = x for i in primes: if t % i == 0: t = t / i break return {t, i} | factors(t) ###Calculates the number of relatively prime numbers up to x @memoize def phi(x): if x in primeSet: return x - 1. for p in primes: c = 0 s = x if x % p == 0: while s % p == 0: c += 1 s = s / p if c == 1: return phi(p) * phi(x / p) else: return phi(s * p) * (p ** (c - 1) * (p - 1))
from utils import is_prime, primes consecutive_primes = [] total = 0 for prime in primes(): total += prime if is_prime(total): consecutive_primes.append(prime) else: break print consecutive_primes
from utils import primes from bisect import bisect_right limit = 10**8 ps = list(primes(limit)) res = 0 for i, p in enumerate(ps): if p * p > limit: break x = limit / p if limit % p: j = bisect_right(ps, x) else: j = bisect_right(ps, x-1) res += j - i print res
import itertools import utils primes = utils.primes(17) def f(n): sn = str(n) for i in range(1, 8): if int(sn[i:i+3]) % primes[i - 1] != 0: return False return True matches = [] for i in itertools.permutations('0123456789', 10): n = int(''.join(i)) if f(n): matches.append(n) print matches print sum(matches)
from itertools import islice from utils import primes # https://docs.python.org/2/library/itertools.html#recipes def nth(iterable, n, default=None): "Returns the nth item or a default value" return next(islice(iterable, n, None), default) n = nth(primes(), 10000) print(n)
def __float__(self): f = 1.0 for (p, a) in zip(utils.primes(), self): f *= p**a return f
import utils primes = utils.primes(7654321) def p(n): sn = str(n) lsn = len(sn) if lsn > 10: return False return set([ int(d) for d in sn ]) == set(range(1, len(sn) + 1)) primes.reverse() for prime in primes: if p(prime): print prime break
def main(): s = 0 primes_larger_than_7 = dropwhile(lambda i: i<10, primes()) print sum(take_11(truncatable_primes(primes_larger_than_7)))
from utils import prime_cache, primes LIMIT = 1_000_000 CACHE = prime_cache(LIMIT) PRIMES = primes(LIMIT) def compute(): max_consec_count = 0 max_consec_count_num = 0 len_primes = len(PRIMES) for i in range(len_primes): consecutive_count = 1 consecutive_sum = PRIMES[i] for j in range(i + 1, len_primes): consecutive_sum += PRIMES[j] consecutive_count += 1 if consecutive_sum >= LIMIT: break elif consecutive_count > max_consec_count and CACHE[ consecutive_sum]: max_consec_count = consecutive_count max_consec_count_num = consecutive_sum return max_consec_count_num if __name__ == "__main__": print(compute())
# # It turns out that the formula will produce 40 primes for the consecutive values n=0 to 39 # # howver, when n = 40, the result is not prime # # n**2 - 79n + 1601 produces 80 consecutive primes for the consecutive values n=0 to 79. the produce of the coefficients -79 and 1601 is -126479 # # considering quadratics of the form n**2 + an + b where abs(a) < 1000 and abs(b) < 1000, find the product of the coefficients a and b for the quadratic expression which produces the maximum number of primes for consective values of n starting with 0 import utils def f(b, c, n): return n**2 + b*n + c primes = utils.primes(10000) maximum = {'prime': 0} for b in range(-1000, 1001): for c in range(-1000, 1001): #print b,c for n in xrange(0, 10000): res = f(b, c, n) if res not in primes: if n > maximum['prime']: maximum['prime'] = n - 1 maximum['b'] = b maximum['c'] = c break print maximum
from utils import primes from utils import is_prime from itertools import combinations PRIMES = primes(10000) def concat_prime(tuple): if len(tuple) != 2: raise AssertionError("concat_prime requires a tuple with 2 numbers") else: if is_prime(int(str(tuple[0]) + str(tuple[1]))) and is_prime( int(str(tuple[1]) + str(tuple[0]))): return True return False def compute(): prime_combos = combinations(PRIMES[1:], 2) # 2 cannot be included return [v for v in prime_combos if concat_prime(v)][:10] if __name__ == "__main__": print(compute())
from utils import primes, is_prime c = 0 s = 0 for p in primes(): if p < 10: continue if c >= 11: break truncations = set([int(str(p)[:i]) for i in range(1, len(str(p)))] + [int(str(p)[i:]) for i in range(1, len(str(p)))]) if all(map(is_prime, truncations)): c += 1 s += p print(s)
from utils import primes ps = set(primes(10**6)) count = 0 for a in range(1, 10000): b = a + 1 p = b**3 - a**3 if p > 10**6: break if p in ps: count += 1 print count
def calc_mods(p): res = [] for i in range(p): j = i * i % p for off in (1, 3, 7, 9, 13, 27): if (j + off) % p == 0: break else: res.append(i) return res limit = 15 * 10**7 res = 0 mods = {p: calc_mods(p) for p in primes(500)} for n in xrange(0, limit + 1, 210): for off in (10, 80, 130, 200): k = n + off possib = True for p in mods: if k * k > p and k % p not in mods[p]: possib = False break if not possib: continue k = (n + off)**2 ps = [] for j in range(k + 1, k + 28, 2): if isprime(j): ps.append(j)
def main(): for p in itertools.islice(utils.primes(), 10000, 10001): print p
import utils primes = set(utils.primes(10**6)) def rotations(n): sn = str(n) return set([ int(sn[i:] + sn[:i]) for i in range(len(sn)) ]) print len(filter(lambda n: rotations(n).issubset(primes), primes.copy()))
return inner @memWays def ways(n, nums): #print n, nums if not nums: return 0 m = nums[0] if(m == n): return 1 + ways(n, nums[1:]) elif(m < n): return ways(n - nums[0], nums) + ways(n, nums[1:]) else: while True: nums = nums[1:n] if not nums: return 0 elif(nums[0] >= n): return ways(n, nums) from utils import primes p = primes(100) from time import time start = time() for x in range(1, len(p)): if ways(x, p) > 5000: print x break print time() - start
def main(): guard = 2000000 print sum(takewhile(lambda x: x<guard, primes()))
from __future__ import print_function from utils import timer, primes, is_permutation, take_between from itertools import dropwhile, takewhile ANSWER = 296962999629 def test_answer(): if ANSWER is None: assert 0, 'Not Completed' else: assert ANSWER == main() PRIMES_WITH_4_DIGITS = list(take_between(1000, 9999, primes())) @timer def main(): for p1 in PRIMES_WITH_4_DIGITS: for p2 in PRIMES_WITH_4_DIGITS: if p2 <= p1: continue p3 = p2 + (p2 - p1) if p3 in PRIMES_WITH_4_DIGITS: if is_permutation(p1, p2) and is_permutation(p2, p3): if p1 == 1487: continue return int(str(p1) + str(p2) + str(p3))
from utils import primes res = 0 for p in primes(10**8): if p < 5: continue res += (p - 3) * pow(8, p - 2, p) % p print res
def main(): cnt = 0 for p in itertools.takewhile(less_than_one_million, utils.primes()): if all(utils.is_prime(i) for i in rotated(p)): cnt += 1 print cnt
def main(): upper_limit = 1000000 prime_numbers = utils.primes(upper_limit) return sum( [circular_prime(prime, prime_numbers) for prime in prime_numbers])
def solve_0(N): return utils.primes(N)[-1]
from utils import primes def f(n, k): res = 0 while n: res += n // k n //= k return res * k n = 20000000 k = 15000000 res = 0 for p in primes(n): res += f(n, p) - f(k, p) - f(n - k, p) print(res)
def product(seq): res = 1 for s in seq: res *= s return res def muls(ps): res = [] for i in range(len(ps) + 1): for comb in combinations(ps, i): res.append(product(comb)) return sorted(res) ps = list(primes(190)) n = len(ps) left = muls(ps[:n // 2]) right = muls(ps[n // 2:]) ans = 0 limit = product(ps)**0.5 from bisect import bisect_left for val in left: i = bisect_left(right, limit / val) if i: ans = max(ans, val * right[i - 1]) print(ans % 10**16)
import utils def is_perm(a, b): return sorted(str(a)) == sorted(str(b)) best = (10000, 1) primes = [ i for i in utils.primes(4000) if i > 2000 ] for i in primes: for j in primes: n = i * j if n > 10**7: break phi = (i - 1) * (j - 1) ratio = (n * 1.0) / phi curr = (ratio, n) if is_perm(n, phi) and curr < best: best = curr print best[1]
def main(n=MILL*2): return sum(takewhile(lambda x: x < n, primes()))
from utils import primes, is_prime as isprime from collections import defaultdict ps = primes(10**4)[1:] concatenable = {p: set() for p in ps} n = len(ps) for p in ps: for q in ps: if isprime(int(str(p) + str(q))): concatenable[p].add(q) for p in ps: for q in concatenable[p]: if q <= p: continue if p not in concatenable[q]: continue for r in concatenable[p] & concatenable[q]: if r <= q: continue if p not in concatenable[r] or q not in concatenable[r]: continue for s in concatenable[p] & concatenable[q] & concatenable[r]: if s <= r: continue if p not in concatenable[s] or q not in concatenable[ s] or r not in concatenable[s]: continue for t in concatenable[p] & concatenable[q] & concatenable[ r] & concatenable[s]: if t <= s: continue if set([p, q, r, s]) <= concatenable[t]: print p, q, r, s, t, p + q + r + s + t
""" from __future__ import print_function from utils import timer, MILL, take_upto, primes ANSWER = 997651 def test_answer(): if ANSWER is None: assert 0, 'Not Completed' else: assert ANSWER == main() PRIMES = list(take_upto(MILL, primes())) PRIME_SET = set(PRIMES) PRIME_SUMS = [PRIMES[0]] # Calculate the cumaltive sum of primes for each step. for psi, p in enumerate(PRIMES[1:]): PRIME_SUMS.append(PRIME_SUMS[psi] + p) @timer def main(): # We use a sliding window to calculate the longest run and its associated # prime. psl = len(PRIME_SUMS) high_run = 0 high_prime = 0