def test_primes(n): # Begin testing primes(n, filename=None) max_p = n output_file = 'primes_list' + str(max_p) + '.txt' start = time.time() primes(max_p, filename=output_file) end = time.time() print("Testing primes({n}, filename={f}), elasped time(s):{T}".format( n=max_p, f=output_file, T=end - start))
def primes(limit): """Get all primes including the first prime above the specified threshold.""" for i in pyprimes.primes(): if i > limit: yield i return yield i
def main(): digits, limit, primes, required = 6, 6, [], 8 for prime in pyprimes.primes(): if prime >= 10 ** digits: break if prime >= 10 ** (digits - 1): primes.append(prime) for prime in list(primes): primes.remove(prime) famillies = {} for other_prime in primes: count, digit, familly = 0, '', 0 for i in xrange(required): if str(other_prime)[i:i + 1] != str(prime)[i:i + 1]: if digit == '' or digit == str(other_prime)[i:i + 1]: digit = str(other_prime)[i:i + 1] count += 1 familly += 2 ** i else: count = limit + 1 break if count <= limit: if familly not in famillies: famillies[familly] = set([other_prime]) if familly in famillies: famillies[familly].add(other_prime) for count in famillies.values(): if len(count) + 1== required: print prime exit()
def test_primes_with_generator(self): # Test the prime generator with a custom generator. # These aren't actually primes. def gen(): yield 3; yield 3; yield 5; yield 9; yield 0 it = pyprimes.primes(strategy=gen) self.assertEqual(list(it), [3, 3, 5, 9, 0])
def __get_prime_pairs(self, rank): """ Determine prime pairs at specified rank Parmeters --------- rank : int the rank of prime pairs to determine """ pit = pyprimes.primes() # intialize p1 = next(pit) this_rank = -1 # find primes while True: p2 = next(pit) if (p2-p1) == 2: this_rank += 1 else: p1 = p2 if this_rank == rank: break return p1, p2
def get_primes_leq(n): primes = [] for p in pyprimes.primes(): if p > n: break primes.append(p) return primes
def test_primes_end_is_exclusive(self): # End argument to primes() is exclusive. n = 211 assert pyprimes.is_prime(n) it = pyprimes.primes(end=n) values = list(it) self.assertEqual(values[-1], 199) assert pyprimes.next_prime(199) == n
def test_primes_start_end(self): # Test the prime generator with both start and end arguments. expected = [ 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499 ] values = list(pyprimes.primes(start=400, end=500)) self.assertEqual(values, expected)
def test_primes_start(self): # Test the prime generator with start argument only. expected = [211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293] assert len(expected) == 16 it = pyprimes.primes(200) values = [next(it) for _ in range(16)] self.assertEqual(values, expected)
def test_primes_start(self): # Test the prime generator with start argument only. expected = [ 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293 ] assert len(expected) == 16 it = pyprimes.primes(200) values = [next(it) for _ in range(16)] self.assertEqual(values, expected)
def main(): prime_pair = dict() existing_set = dict() PAIR_COUNT = 5 for single_prime in primes(): # split prime into char combinations str_prime = str(single_prime) for break_pos in range(1, len(str_prime)): left = int(str_prime[:break_pos]) right = int(str_prime[break_pos:]) if left != 0 and right != 0 and isprime(left) and isprime( right) and left != right: if int(str(right) + str(left)) < single_prime: continue if isprime(int(str(right) + str(left))): # put this two prime pair into cache # and left is definitely smaller than right if left not in existing_set: existing_set[left] = list() existing_set[left].append(list({right})) else: for idx, single_set in enumerate(existing_set[left]): for prime in single_set: if not isprime( int(str(right) + str(prime))) or not isprime( int(str(prime) + str(right))): break else: existing_set[left][idx].append(right) if len(existing_set[left] [idx]) == PAIR_COUNT - 1: existing_set[left][idx].append(left) return existing_set[left][idx] existing_set[left].append(list({right})) if right not in existing_set: existing_set[right] = list() existing_set[right].append(list({left})) else: for idx, single_set in enumerate(existing_set[right]): for prime in single_set: if not isprime( int(str(left) + str(prime))) or not isprime( int(str(prime) + str(left))): break else: existing_set[right][idx].append(left) if len(existing_set[right] [idx]) == PAIR_COUNT - 1: existing_set[right][idx].append(right) return existing_set[right][idx] existing_set[right].append(list({left}))
def test_primes_with_generator(self): # Test the prime generator with a custom generator. # These aren't actually primes. def gen(): yield 3 yield 3 yield 5 yield 9 yield 0 it = pyprimes.primes(strategy=gen) self.assertEqual(list(it), [3, 3, 5, 9, 0])
def main(): target = Fraction(15499, 94744) f = Fraction(1) d = 1 for prime in primes(): f *= Fraction(prime-1, prime) d *= prime if f < target: break n = int(f * d) for k in count(1): if Fraction(n * k, d * k -1) < target: break print k * d
def main(): primes, truncatable_primes = [], [] for prime in pyprimes.primes(): is_truncatable_prime = True for i in xrange(len(str(prime)) - 1): if int(str(prime)[i + 1:]) not in primes or int(str(prime)[:-i - 1]) not in primes: is_truncatable_prime = False break if is_truncatable_prime: truncatable_primes.append(prime) if len(truncatable_primes) == 15: break primes.append(prime) print sum(truncatable_primes[4:])
def main(): sums = [] for prime in pyprimes.primes(): if len(sums) == 0: sums.append(prime) continue if prime + sums[len(sums) - 1] >= 1000000: break sums.append(prime + sums[len(sums) - 1]) maximum_length, maximum_value = 0, 0 for i in xrange(0, len(sums) - 1): for j in xrange(i, len(sums)): if j - i > maximum_length and pyprimes.isprime(sums[j] - sums[i]): maximum_length, maximum_value = j - i, sums[j] - sums[i] print maximum_value
def main(): to_add_in = set() prime_combinations = set([]) print merged_numbers_are_not_prime(3, 7) for prime in primes(): to_include = set([frozenset([prime])]) for prime_combo in prime_combinations: if can_include(prime_combo, prime): to_add_in = deepcopy(prime_combo) to_add_in.add(prime) if len(to_add_in) == 2: print to_add_in return to_include.add(to_add_in) prime_combinations |= to_include print prime_combinations
def main(): n, primes = 2, [] for prime in pyprimes.primes(): if prime > 1000: break primes.append(prime) while True: ways = [0 for i in xrange(n + 1)] ways[0] = 1 for i in xrange(len(primes)): for j in xrange(primes[i], n + 1): ways[j] += ways[j - primes[i]] if ways[len(ways) - 1] > 5000: break n += 1 print n
class CompressionAlgorithm(Core): """A compression algorithm is a set of two function: - compress - decompress Decompress is the inverse of compress.""" PRIMES = pyprimes.primes() def _init(self, algorithm_name): """Algorithm name is used to get unique names""" self.name = algorithm_name self.const = next(CompressionAlgorithm.PRIMES) self.constraints = list() self._createCompressionFunction() def _addConstraints(self, solver): solver.add(self.constraints) def _createCompressionFunction(self): """Declare functions add some constraints to this etc""" self.compress = z3.Function('%s_compress' % (self.name), z3.IntSort(), z3.IntSort()) self.decompress = z3.Function('%s_decompress' % (self.name), z3.IntSort(), z3.IntSort()) uncompressed = z3.Const('__compression_%s_uncompressed' % (self.name), z3.IntSort()) # Assume that compression changes data, because well that makes sense self.constraints.append( z3.ForAll([uncompressed], self.compress(uncompressed) == uncompressed + self.const)) self.constraints.append( z3.ForAll([uncompressed], self.decompress(uncompressed) == uncompressed - self.const)) # Decompression is the inverse of compression self.constraints.append(z3.ForAll([uncompressed],\ self.decompress(self.compress(uncompressed)) == uncompressed)) def packetCompressionPredicate(self, context): return lambda p: self.compress(context.packet.body(p)) def packetDecompressionPredicate(self, context): return lambda p: self.decompress(context.packet.body(p))
def main(): powers, primes, results = [[] for i in xrange(3)], [], set() for prime in pyprimes.primes(): if prime > 7071: break primes.append(prime) for prime in primes: for i in xrange(3): powers[i].append(prime ** (i + 2)) for i in xrange(len(powers[0])): for j in xrange(len(powers[1])): for k in xrange(len(powers[2])): l = powers[0][i] + powers[1][j] + powers[2][k] if l > 50000000: break results.add(l) print len(results)
def main(): minimum, minimum_p, primes = 10 ** 7, 0, [] for prime in pyprimes.primes(): if prime > 5000: break if prime >= 2000: primes.append(prime) for p1 in primes: for p2 in primes: p = p1 * p2 if p < 10 ** 7: totient = (p1 - 1) * (p2 - 1) if sorted(str(p)) == sorted(str(totient)): if float(p) / float(totient) < minimum: minimum = float(p) / float(totient) minimum_p = p print minimum_p
def __get_prime_pairs(self, rank): pit = pyprimes.primes() # intialize p1 = next(pit) this_rank = -1 # find primes while True: p2 = next(pit) if (p2 - p1) == 2: this_rank += 1 else: p1 = p2 if this_rank == rank: break return p1, p2
def main(): result = 0 i = 0 print 'upper bound: ', ub for p in pyprimes.primes(): if p > ub: break if p < 9000000: continue i += 1 if i % 50000 == 0: print i, '/', 1797049, '(', i / 1797049.0, ')' if chain_length(p - 1) == 24: result += p print result
def numFactors(n): ct = 0 l = [] temp = n p = pyprimes.primes() for i in p: l.append(0) while temp%i==0: l[ct] += 1 temp = temp/i ct += 1 if temp==1: break num = 1 for i in l: num *= i+1 return num
def main(): primes = [] for prime in pyprimes.primes(): if prime >= 10000: break primes.append(prime) for a in primes: for b in primes: if not can_concatenate(b, [a]): continue for c in primes: if not can_concatenate(c, [a, b]): continue for d in primes: if not can_concatenate(d, [a, b, c]): continue for e in primes: if can_concatenate(e, [a, b, c, d]): print a + b + c + d + e exit()
def factors(n): """factors(integer) -> yield factors of integer lazily >>> list(factors(3*7*7*7*11)) [(3, 1), (7, 3), (11, 1)] Yields tuples of (factor, count) where each factor is unique and usually prime, and count is an integer 1 or larger. The factors are prime, except under the following circumstances: if the argument n is negative, -1 is included as a factor; if n is 0 or 1, it is given as the only factor. For all other integer n, all of the factors returned are prime. """ if n in (0, 1, -1): yield (n, 1) return elif n < 0: yield (-1, 1) n = -n assert n >= 2 from pyprimes import primes for p in primes(): if p * p > n: break count = 0 while n % p == 0: count += 1 n //= p if count: yield (p, count) if n != 1: if __debug__: # The following test only occurs if assertions are on. if _EXTRA_CHECKS: from pyprimes import is_prime assert is_prime(n), ('final factor %d is not prime' % n) yield (n, 1)
def factors(n): """factors(integer) -> yield factors of integer lazily >>> list(factors(3*7*7*7*11)) [(3, 1), (7, 3), (11, 1)] Yields tuples of (factor, count) where each factor is unique and usually prime, and count is an integer 1 or larger. The factors are prime, except under the following circumstances: if the argument n is negative, -1 is included as a factor; if n is 0 or 1, it is given as the only factor. For all other integer n, all of the factors returned are prime. """ if n in (0, 1, -1): yield (n, 1) return elif n < 0: yield (-1, 1) n = -n assert n >= 2 from pyprimes import primes for p in primes(): if p*p > n: break count = 0 while n % p == 0: count += 1 n //= p if count: yield (p, count) if n != 1: if __debug__: # The following test only occurs if assertions are on. if _EXTRA_CHECKS: from pyprimes import is_prime assert is_prime(n), ('final factor %d is not prime' % n) yield (n, 1)
def main(): global s global sUB global hits global misses print "S = takeWhile (< ", sUB, ") P.primes" print "Number of subsets of S that sum to a prime number: ", result = 0 ssum = sum(s) maxUsablePrime = max(s) for p in pyprimes.primes(): # `sum s` is for the subset that is `S`; the maximal subset if not p <= ssum: break # `+ 1` because of noninclusiveness result += numFormations(p, min(p + 1, maxUsablePrime + 1)) result %= 10000000000000000 print result # print 'cache size: ', len(memo) print 'hits: ', hits print 'misses: ', misses
def test_primes_end(self): # Test the prime generator with end argument only. expected = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] it = pyprimes.primes(end=50) self.assertEqual(list(it), expected)
import pyprimes def add_test(prime_num): str_prime_num = str(prime_num) for i in range(1, len(str_prime_num)): right = pyprimes.is_prime(int(str_prime_num[0:i])) left = pyprimes.is_prime(int(str_prime_num[i:len(str_prime_num)])) if right and left: continue else: return list.append(prime_num) ############################################################################ list = [] p = pyprimes.primes() for prime_num in p: if len(list) == 11: break if prime_num > 10: add_test(prime_num) print list print sum(list)
# 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. # # Darren Brain # [email protected] # 2/28/2016 from pyprimes import primes total = 0 prime_list = primes(2,2000000) for prime_num in prime_list: total += prime_num print(total)
import pyprimes m = 0 for n, p in enumerate(pyprimes.primes()): r = ((p - 1) ** n + (p + 1) ** n) % (p ** 2) if r > m: m = r print n, r if r > 10 ** 9: print n break
# The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143? import pyprimes lastPrime = 0 it = 0 for i in pyprimes.primes(): it += 1 if it % 1000000 == 0: print i, '/', 600851475143/2 if 600851475143%i == 0: print i lastPrime = i print lastPrime
def test_primes_start_is_inclusive(self): # Start argument to primes() is inclusive. n = 211 assert pyprimes.is_prime(n) it = pyprimes.primes(start=n) self.assertEqual(next(it), n)
import pyprimes import itertools import math import time start = time.time() numList = [] below = 5000000 cUpper = math.ceil(below**(4**-1)) primeList = list(pyprimes.primes(2, math.ceil(math.sqrt(50000000)))) cList = primeList[:pyprimes.prime_count(cUpper - 1)] for i in range(len(cList) - 1, -1, -1): csquare = cList[i]**4 bUpper = math.ceil((below - csquare)**(3**-1)) bList = primeList[:pyprimes.prime_count(bUpper - 1)] for j in range(len(bList) - 1, -1, -1): bsquare = bList[j]**3 aUpper = math.ceil(math.sqrt(below - csquare - bsquare)) aList = primeList[:pyprimes.prime_count(aUpper - 1)] for k in range(len(aList) - 1, -1, -1): result = (aList[k]**2 + bsquare + csquare) if result not in numList: numList.append(result) print(len(numList))
if p1[0] == '0' or p2[0] == '0': continue if pyprimes.isprime(int(p1)) and pyprimes.isprime( int(p2)) and pyprimes.isprime(int(str(p2) + str(p1))): result.append([int(p1), int(p2)]) return result existing_sets = [] target = 5 found_match = False for p in pyprimes.primes(): prime_pairs = check_has_pair(p) if not prime_pairs: continue for pair in prime_pairs: found = [False, False] for existing in existing_sets: for i, p in enumerate(pair): if p in existing: found[i] = True else: valid = True for op in existing:
def test_primes_end_none(self): # Check that None is allowed as an end argument. it = pyprimes.primes(end=None) self.assertEqual(next(it), 2)
""" Summation of primes 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 primegen import prime_generator # prime = prime_generator() from pyprimes import primes prime = primes() prime_sum = 0 while 1: p = prime.next() if p > 2e6: break prime_sum += p print p print prime_sum
"""# 10001st prime [Problem 7](https://projecteuler.net/problem=7) By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number?""" from pyprimes import primes for n, p in enumerate(primes()): if n == 10001: print(f'{n}: {p}') break
import pyprimes def cumulativeSum(l): sum = 0 i = 0 for num in l: i+=1 sum += num yield (sum,i) def possibleConsecutiveSums(l): for i in xrange(len(l)): for num in cumulativeSum(l[i:]): yield num primesSmallEnough = [] for num in pyprimes.primes(): if sum(primesSmallEnough) > 10**6: break primesSmallEnough.append(num) print 'done', len(primesSmallEnough) toPrint = [x for x in possibleConsecutiveSums(primesSmallEnough) if x[0]<10**6 and pyprimes.isprime(x[0])] print 'done', len(toPrint) justSecondNums = [x[1] for x in toPrint] print toPrint[justSecondNums.index(max(justSecondNums))]
def test_primes_start_end(self): # Test the prime generator with both start and end arguments. expected = [401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499] values = list(pyprimes.primes(start=400, end=500)) self.assertEqual(values, expected)
x += '0' x += '1' while result < J: isJamCoin = True for base in range(2, 11): isJamCoin = isJamCoin and not (pyprimes.isprime(int(x, base))) if isJamCoin: turn2Proof = 0 proof = [] for base in range(2, 11): y = int(x, base) primesGenerator = pyprimes.primes() p = 2 turn2Proof = 0 while y % p > 0 and turn2Proof < maxProofTurn: turn2Proof += 1 p = next(primesGenerator) if turn2Proof == maxProofTurn: isJamCoin = False proof.append(p) if isJamCoin: resultStr = '' + str(x) for z in proof: resultStr += ' ' + str(z)
ll = cycle(l) cycles = [l] while (ll != l): cycles.append(ll) ll = cycle(ll) return cycles def is_circular_prime(p): l = map(pyprimes.isprime, map(int, (gen_cycles(str(p))))) for b in l: if not b: return False return True def filter(P, l): ll = [] for e in l: if P(e): ll.append(e) return ll UB = 1000000 primes_under_ub = [] for p in pyprimes.primes(): if p > UB: break primes_under_ub.append(p) l = filter(is_circular_prime, primes_under_ub) sought = len(l)
def equation(a,b,n): return n*n + a*n +b def worksUpUntil(a,b,primeNums, max): for i in xrange(max): if equation(a,b,i) not in primeNums: return i return -1 primeNums = set([]) max = 1000 for p in pyprimes.primes(): if p > max: break primeNums.add(p) currMax = 0 currCoefMultiplies = 0 for a in xrange(-max,max): for b in pyprimes.primes(): if b > max: break tempWorksUntil = worksUpUntil(a,b,primeNums, max) if(tempWorksUntil > currMax): currMax = tempWorksUntil currCoefMultiplies = a*b print currCoefMultiplies
# 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. # # Darren Brain # [email protected] # 2/28/2016 from pyprimes import primes total = 0 prime_list = primes(2, 2000000) for prime_num in prime_list: total += prime_num print(total)
1 | 0 |______________________ 1 2 3 4 5 6 7 ... 4999 # max usable prime (sUB) ''' def takeWhile(p, xs): result = [] for x in xs: if not p(x): break result.append(x) return result sUB = 200 #5000 s = takeWhile(lambda p: p < sUB, pyprimes.primes()) hits = 0 misses = 0 # | Number of ways to form `n` as a summation of primes less than `maxPrime` # (note the non-inclusiveness in the second parameter) memo = dict() # @profile def numFormations(n, maxPrime): if (n == 0): return 1 # formation is the empty set global s global hits global misses