def prime_powers(n): ''' Return dict where keys are primes and values are exponents. Represents prime factorization of 'n!' ''' powers = dict() for p in primes(n): powers[p] = legendre(p, n) return powers
def longest_recurring(n): for d in primes(n)[::-1]: p = 1 while pow(10, p, d) != 1: p += 1 if d - 1 == p: return d
def main(): ''' Driver function ''' n, m = 20 * 10**6, 15 * 10**6 total = 0 for p in primes(n): total += p * (legendre(n, p) - legendre(m, p) - legendre(n - m, p)) print(total)
def getSolution(limit): result = 1 for prime in pyprimesieve.primes(limit): power = 1 while prime ** (power + 1) <= limit: power += 1 result *= prime ** power return result
def main(): ''' Driver function ''' end = 40000000 chain_lengths = [0] * end total = 0 for p in primes(end): if prime_chain_length(p, chain_lengths) == 25: total += p print(total)
def path_to_roots(bitmask): ''' Generator of lists containing the values between 'p' and its digital root. Values are represented using 'bitmask' ''' for p in primes(10**7, 2 * 10**7): cur = [] while p > 9: digits = [int(n) for n in str(p)] cur += [[bitmask[d] for d in digits]] p = sum(digits) yield cur + [[bitmask[p]]]
def main(): ''' R(k) is equal to (10**k-1)/9. Thus, a number n divides R(k) IFF (10**k-1)/9 = 0 (mod n). This can be re-arranged to 10**k = 1 (mod 9*n), which allows for the use of modular exponentiation ''' factors = [] for n in primes(10**6): if pow(10, 10**9, 9*n) == 1: factors += [n] if len(factors) == 40: break print(sum(factors))
def maximise_quad(): max_seq = A = B = 0 quad = lambda n, a, b: n * n + a * n + b cache = set(pp.primes(100000)) for a in range(-999, 1000, 1): for b in range(-1000, 1001, 1): n = 0 while (x := quad(n, a, b)) in cache: n += 1 if n > max_seq: A, B, max_seq = a, b, n
def get_vals(end): ''' This post explains it: https://bit.ly/2J9ByKf ''' vals = primes(end) n = 0 while vals[n] < end**0.5: val, l = 0, 1 while val < end: val = vals[n]**2**l vals.append(val) l += 1 n += 1 return sorted(vals)
def find_num_divisors(end): ''' Calculate the number of divisors for each number up to 'end' ''' num_divisors = [0 for _ in range(2, end)] prime = set(primes(10**7)) for n in range(2, end): divisors = 1 if n not in prime: factors = factorize(n) for _, e in factors: divisors *= (e + 1) num_divisors[n - 2] = divisors return num_divisors
def main(): ''' The solution must be > 1000000 as A(n) < n. This function iterates over valid values of 'n' (not prime and not divisible by 2 or 5) starting at 2 until 25 solutions are found. The sum of these solutions is then printed ''' found = [] prime = set(primes(100000)) for n in count(2): if n not in prime and n % 2 and n % 5 and (n - 1) % brute_check(n) == 0: found += [n] if len(found) == 25: break print(sum(found))
def main(): ''' 'n' must be a cube. This function iterates over all cubes up to 600^3 for each prime. 'found' keeps track of the number of valid '(n, p)' pairs. This amount is printed at the end. This solution is relatively slow (about 30 seconds) ''' found = 0 cubes = [n**3 for n in range(1, 600)] for p in primes(1000000): for n in cubes: cur = n * n * (n + p) if round(cur**(1 / 3))**3 == cur: found += 1 break print(found)
def S(n): ''' Uses Goldbach's conjecture, which has been verified for integers in the range required by the problem. The sum of all P(m, 1) for 1 <= m <= n is the number of primes <= n. The sum of all P(m, 2) is the number of even integers in 4 <= m <= n plus the number of integers in 6 <= m <= n equal to a prime plus 2. The sum of all P(m, k) with k >= 3 is the sum of all integers in 6 <= m <= n floor divided by 2 minus 2 (subtract 2 for each m or subtract 2*(n-6) once). 'P_n_k' is a closed form expression that calculates this ''' prime = primes(n + 1) P_n_1 = len(prime) P_n_2 = 0 if n < 4 else (n // 2) - 1 + (prime[-1] + 2 <= n) + P_n_1 - 2 P_n_k = 0 if n < 6 else (ceil((7 - n) / 2)**2 - 7 * ceil( (7 - n) / 2) + (n // 2)**2 + (n // 2) - 4 * n + 20) // 2 return P_n_1 + P_n_2 + P_n_k
def general_hamming(end, high): ''' Return a set of all numbers (<= end) with prime factors not exceeding high ''' hamming = {1} prev = {1} base = primes(high+1) while 2*min(prev) <= end: cur = set() for n in prev: for p in base: temp = n*p if temp > end: break cur.add(temp) hamming.update(cur) prev = cur return hamming
def find_goldbach(): primes = pp.primes(N) cache = set(primes) sq2 = [2 * (n * n) for n in range(1, N)] i = 9 while (i < N): if not i in cache: lt = lambda x: x < i result = False for a in takewhile(lt, sq2): for b in takewhile(lt, primes): if a + b == i: result = True break if result: break if not result: return i i += 2
def test_1(self): self.assertEqual(pyprimesieve.primes(1), [])
def pyprimesieve(n): import pyprimesieve return list(pyprimesieve.primes(n))
def sumofprimes(n): # lambda expression is slower return sum(primes(n))
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # projecteuler.net # # problem 41 # import pyprimesieve primes = pyprimesieve.primes(7654321) def pandigital(n): s = str(n) if ''.join(sorted(s)) == "1234567": return True return False for p in reversed(primes): if pandigital(p): print(p) exit(0)
def test_emptylist_2(self): self.assertEqual(pyprimesieve.primes(-1), [])
def test_prime_count_2(self): self.assertEqual(len(pyprimesieve.primes(10**8)), 5761455)
def test_prime_count_1(self): self.assertEqual(len(pyprimesieve.primes(10**7)), 664579)
def test_4(self): self.assertEqual(pyprimesieve.primes(4), [2, 3])
def test_3(self): self.assertEqual(pyprimesieve.primes(3), [2])
def test_2(self): self.assertEqual(pyprimesieve.primes(2), [])
def test_ranges_1(self): # start > n self.assertEqual(pyprimesieve.primes(411, 42), [])
def test_ranges_2(self): # start < 0 - should be uneffected as if it were 2 self.assertTrue(sequences_equal(pyprimesieve.primes(-100, 42), primes(42)))
def test_bignums_2(self): self.assertEqual(pyprimesieve.primes_sum(10**6), sum(pyprimesieve.primes(10**6)))
def test_ranges_3(self): # arbitrary point to start self.assertTrue(sequences_equal(pyprimesieve.primes(1412, 85747), dropwhile(lambda n: n < 1412, primes(85747))))
def test_ranges_4(self): # arbitrary point to start self.assertTrue(sequences_equal(pyprimesieve.primes(74651, 975145), dropwhile(lambda n: n < 74651, primes(975145))))
result = 0 for num in droots: result += 2*aroot(num) return result def maxclock(n): n_copy = str(n) droots = [n_copy] while int(n_copy) >= 10: n_copy = droot(n_copy) droots.append(n_copy) result = aroot(droots[0]) for i, num in enumerate(droots[1:]): prev = droots[i] cur = num diff = len(prev) - len(cur) result += aroot(prev[:diff]) for i, dig in enumerate(cur): result += chdict[(prev[diff+i], dig)] result += aroot(droots[-1]) return result import pyprimesieve as pp result = 0 for p in pp.primes(2*10**7): if p>10**7: s = samclock(p) m = maxclock(p) result += (s-m) print result
from math import log import pyprimesieve as pp import sys sys.setrecursionlimit(5000) def max_primepow(n, prime): if n < prime: return 0 return int(log(n)/log(prime)) myprimes = set(pp.primes(10)) def gen_admissible(n, prodprimes=1, lastprime=1, admiss=[1]): nextprime = None for num in xrange(lastprime+1, 6): if num in {2, 3, 5}: nextprime = num prodprimes = prodprimes * nextprime break if not nextprime: return admiss else: newadmiss = [] for base in sorted(admiss): max_pow = max_primepow(n/base, nextprime) if not max_pow: break newadmiss += [base*nextprime**i for i in xrange(1, max_pow+1)]
import pyprimesieve as pp import sys from itertools import product from operator import mul sys.setrecursionlimit(2000) gazinga_cache = {1: 1} prime = pp.primes(45) def isvalid(combo, nmax=10**9): num = 1 for i, n in enumerate(combo): num = num * prime[i]**n return num < nmax, num def firstidx(combo): idx = 0 for i in xrange(len(combo)-1, 0, -1): if combo[i] < combo[i-1]: idx = i break combo[idx] += 1 newcombo = combo[:idx+1] + [1]*len(combo[idx+1:]) return idx, newcombo def secondidx(combo, nmax=10**9):
def prime_sieve(n): """ Finds all primes from 1 until n """ import pyprimesieve return pyprimesieve.primes(int(n))
#! /usr/bin/env python # -*- coding: utf-8 -*- # projecteuler.net # # problem 27 # from pyprimesieve import primes s = 0 c = (0, 0) p = set(primes(751000)) for a in range(-999, 0, 2): for b in range(-a, 1000, 2): n = 1 while (n * (n + a) + b) in p: n += 1 if n > s: s = n c = (a, b) print(c[0] * c[1])
sequences_equal(pyprimesieve.primes(-100, 42), primes(42))) def test_ranges_3(self): # arbitrary point to start self.assertTrue( sequences_equal( pyprimesieve.primes(1412, 85747), itertools.dropwhile(lambda n: n < 1412, primes(85747)))) def test_ranges_4(self): # arbitrary point to start self.assertTrue( sequences_equal( pyprimesieve.primes(74651, 975145), itertools.dropwhile(lambda n: n < 74651, primes(975145)))) def sequences_equal(lst1, lst2): return all(a == b for a, b in zip_longest(lst1, lst2)) for i, n in enumerate( xrange(100, 10000, 100) ): # create sequence comparison tests for sieves of size n in range test = lambda self: self.assertTrue( sequences_equal(pyprimesieve.primes(n), primes(n))) setattr(TestPrimes, 'test_' + str(i), test) if __name__ == "__main__": unittest.main()
# start > n self.assertEqual(pyprimesieve.primes(411, 42), []) def test_ranges_2(self): # start < 0 - should be uneffected as if it were 2 self.assertTrue(sequences_equal(pyprimesieve.primes(-100, 42), primes(42))) def test_ranges_3(self): # arbitrary point to start self.assertTrue(sequences_equal(pyprimesieve.primes(1412, 85747), dropwhile(lambda n: n < 1412, primes(85747)))) def test_ranges_4(self): # arbitrary point to start self.assertTrue(sequences_equal(pyprimesieve.primes(74651, 975145), dropwhile(lambda n: n < 74651, primes(975145)))) def sequences_equal(lst1, lst2): return all(a == b for a, b in izip_longest(lst1, lst2)) primes = _primes_numpy if HAS_NUMPY else _primes for i, n in enumerate(xrange(100, 10000, 100)): # create sequence comparison tests for sieves of size n in range test = lambda self: self.assertTrue(sequences_equal(pyprimesieve.primes(n), primes(n))) setattr(TestPrimes, 'test_' + str(i), test) if __name__ == "__main__": unittest.main()
from math import sqrt, log import pyprimesieve as pp import sys sys.setrecursionlimit(5000) def max_primepow(n, prime): if n < prime: return 0 return int(log(n)/log(prime)) myprimes = set(pp.primes(10**9)) def gen_admissible(n, prodprimes=1, lastprime=1, admiss=[1], valids=[1]): nextprime = None for num in xrange(lastprime+1, int(sqrt(n))+1): if num in myprimes: nextprime = num prodprimes = prodprimes * nextprime break if not nextprime: return admiss else: newadmiss = [] for base in sorted(valids): max_pow = max_primepow(n/base, nextprime) if not max_pow: break newadmiss += [base*nextprime**i for i in xrange(1, max_pow+1)]
def test_ranges_3(self): # arbitrary point to start self.assertTrue( sequences_equal( pyprimesieve.primes(1412, 85747), itertools.dropwhile(lambda n: n < 1412, primes(85747))))
def test_ranges_2(self): s = pyprimesieve.primes_sum(7, 22) self.assertEqual(s, 67) self.assertEqual(s, sum(pyprimesieve.primes(22)[3:]))
def test_ranges_1(self): s = pyprimesieve.primes_sum(3, 13) self.assertEqual(s, 26) self.assertEqual(s, sum(pyprimesieve.primes(13)[1:]))
import pyprimesieve as pp from benchmark import timed max_prime = 1000000 primes = pp.primes(max_prime) max_idx = len(primes) - 1 cache = set(primes) # optimize: # work from max slice down (and return first result), not min slice up @timed def find_longest_slice(min_slice): result = 0 longest_slice = min_slice for idx in range(0, max_idx - min_slice): slice = min_slice while (subset := sum(primes[idx:idx + slice])) <= max_prime: if subset in cache: if slice > longest_slice: longest_slice = slice result = subset slice += 1 return (result, longest_slice, idx) result = find_longest_slice(21) print(result)
import pyprimesieve as pp primes = set(pp.primes(500)) from collections import defaultdict from fractions import Fraction as F def shoutprob(yelp, k): res = F(1, 3) * (F(1) + F(k in primes)) if yelp == 'P': return res else: return F(1) - res def getjumps(k, n=500): if k == 1: return {k+1: F(1)} elif k == n: return {k-1: F(1)} else: return {k-1: F(1, 2), k+1: F(1, 2)} def movefrog(yelp, possib): newpossib = defaultdict(F) for k, prob in possib.iteritems(): for j, jprob in getjumps(k).iteritems(): newpossib[j] += prob*shoutprob(yelp, k)*jprob return newpossib
def test_ranges_2(self): # start < 0 - should be uneffected as if it were 2 self.assertTrue( sequences_equal(pyprimesieve.primes(-100, 42), primes(42)))
import pyprimesieve # Library from here: https://pypi.python.org/pypi/pyprimesieve first_number = "1"+"0"*30+"1" last_number = "1"+"1"*30+"1" first_thousand_primes = pyprimesieve.primes(5000) def is_prime_in_base(num_str, base): n = int(num_str, base=base) for i in first_thousand_primes: if n %i ==0: return i return -1 print "Case #1:" J = 0 current_number = first_number while J!=500: factors = [] correct = True for base in xrange(2,10+1): # for each base factor = is_prime_in_base(current_number, base) if factor != -1: factors.append(factor) else: correct = False break if correct: print current_number, for factor in factors: print factor, print "" J+=1
def test_ranges_4(self): # arbitrary point to start self.assertTrue( sequences_equal( pyprimesieve.primes(74651, 975145), itertools.dropwhile(lambda n: n < 74651, primes(975145))))
import pyprimesieve as pp from collections import defaultdict primelst = pp.primes(10**7) myprimes = set(primelst) def isprime(n): return n in myprimes def changedigit(n): str_n = str(n) edges = defaultdict(set) for i, dig in enumerate(str_n): alldigs = [str(x) for x in range(10) if str(x) != dig] if i == 0: alldigs.pop(0) for newdig in alldigs: testprime = str_n[:i] + newdig + str_n[i+1:] testprime = int(testprime) if isprime(testprime): edges[testprime].add(n) return edges def adddigit(n): str_n = str(n) edges = defaultdict(set) alldigs = [str(x) for x in range(1, 10)] for newdig in alldigs: testprime = newdig + str_n