Exemple #1
0
 def reduce(self):
     if self.numerator == 0:
         return Fraction(0, 1)
     primes = sieve(max(self.numerator, self.denominator))
     num = self.numerator
     den = self.denominator
     num_factors = []
     den_factors = []
     for p in primes:
         while num % p == 0:
             num_factors.append(p)
             num //= p
         while den % p == 0:
             den_factors.append(p)
             den //= p
     reduced_num = 1
     for x in num_factors:
         if x in den_factors:
             den_factors.remove(x)
         else:
             reduced_num *= x
     reduced_den = 1
     for y in den_factors:
         reduced_den *= y
     return Fraction(reduced_num, reduced_den)
Exemple #2
0
def run():
    n = 1
    limit = 10**10
    primes = euler.sieve()
    while True:
        pn = next(primes)
        modulus = pn**2
        remainder = (pow(pn-1, n, modulus) + pow(pn+1, n, modulus)) % modulus
        if remainder >= limit:
            return n
        n += 1
Exemple #3
0
def main():
  primes = set([x for x in sieve(6000)])

  for i in range (33, 6000, 2):
    if i in primes:
      continue
    isCool = True
    for sq in [x**2 for x in range(i/2)]:
      if i - 2 * sq in primes:
        isCool = False
    if isCool:
      print i
      return
Exemple #4
0
import euler

q1 = lambda x : (2*x+1)**2
q2 = lambda x : q1(x) - 2*x
q3 = lambda x : q1(x) - 4*x
q4 = lambda x : q1(x) - 6*x

q = [ q2, q3, q4 ]

maxprime = 14000
lowPrimes = euler.sieve(maxprime)
lowPrimes = set(lowPrimes)
def isprime(n):
    if n < maxprime:
        return n in lowPrimes
    else:
#        return euler.isprime_slow(n)
        return euler.isprime(n)

@euler.in_mem_memoize
def nprimes(x):
    cnt = 0
    for qi in q:
        if isprime(qi(x)):
            cnt += 1
    return cnt

def primesInLayer(n):
    cnt = 0
    for i in range(n):
        cnt += nprimes(i)
Exemple #5
0
import sys
sys.path.append("..")
from euler import sieve, concatenate
from collections import defaultdict
from itertools import combinations, chain


def is_valid(sequence):
    dif = sequence[1] - sequence[0]
    return sequence[2] - sequence[1] == dif


primes = sieve(10000)
primes = {x for x in primes if x > 1000}

perms = defaultdict(list)

for p in sorted(primes):
    p_string = ''.join(sorted(str(p)))
    perms[p_string].append(p)

perms = filter(lambda x: len(x) >= 3, perms.values())
perms = (list(combinations(x, r=3)) for x in perms)
perms = chain.from_iterable(perms)
valid = filter(is_valid, perms)
valid = list(filter(lambda x: x[0] != 1487, valid))
valid = concatenate(valid[0])

print(valid)
import euler
import collections
import sys

lst = euler.sieve(10000)
lst = [i for i in lst if i >= 1000]
print len(lst)


def isPerm(a, b):
    return set(euler.intToSeq(a)) == set(euler.intToSeq(b))


def seqPoints(seq):
    for i in range(len(seq)):
        for j in range(i + 1, len(seq)):
            for k in range(j + 1, len(seq)):
                yield [seq[idx] for idx in [i, j, k]]


def isArithmeticSeq(seq):
    for i in seqPoints(seq):
        a, b, c = tuple(i)
        if c - b == b - a:
            return True, str(a) + str(b) + str(c)
    return False, ''


d = collections.defaultdict(set)
seen = set()
for i in lst:
Exemple #7
0
import euler

primes = [p for p in euler.sieve(10000) if p >= 1000]
primeset = set(primes)


def check(a, b, c):
    sa, sb, sc = [list(sorted(str(i))) for i in [a, b, c]]
    return sa == sb == sc


for i, p1 in enumerate(primes):
    for i2 in range(i + 1, len(primes)):
        p2 = primes[i2]
        p3 = p1 + 2 * (p2 - p1)
        if p3 in primeset and check(p1, p2, p3):
            print(p1, p2, p3)
Exemple #8
0
import euler
import math
import sys
import itertools


def cycles(p):
    size = math.floor(math.log(p, 10) + 1)
    for i in range(size):
        yield p
        last = p % 10
        p = p // 10 + (last * 10**(size - 1))


primes = list(euler.sieve(10**6))
circular = set([2, 3, 5, 7])
seen = set()
for size in range(2, 7):
    for plist in itertools.product([1, 3, 7, 9], repeat=size):
        p = int("".join(str(i) for i in plist))
        if p in circular or p in seen:
            continue
        if all(c in primes for c in cycles(p)):
            circular.update(cycles(p))
        else:
            seen.update(cycles(p))
print(len(circular))
Exemple #9
0
#!/usr/bin/python
import euler

UpTo = 1000000

primes = euler.sieve(UpTo)
circular = [0] * len(primes)


def rotate(d):
    return d[-1:] + d[:-1]


for x in range(0, len(primes)):
    if not primes[x]:
        continue
    if circular[x]:
        continue
    d = rotate(euler.digits(x))
    rd = euler.num_from_digits(d)
    while rd != x:
        if not primes[rd]:
            break
        d = rotate(d)
        rd = euler.num_from_digits(d)

    if rd == x:
        d = rotate(d)
        rd = euler.num_from_digits(d)
        circular[x] = 1
        while rd != x:
Exemple #10
0
import math
import euler

maxv = 1000000
primes = euler.sieve(maxv)

def primeFactors(n):
    factors = []
    for p in primes:
        if p > n:
            break
        if n % p == 0:
            factors.append(p)
    return factors

def sieve(n):
    nfactors = [ 0 for i in xrange(n) ]
    for p in primes:
        if p > n:
            break
        for v in xrange(p,n,p):
            nfactors[v] += 1
    return nfactors

pick = -1
nfactors = sieve(maxv)
rest = [ i for n,i in zip(nfactors,xrange(maxv)) if n == 4 ]
for i in range(len(rest)-4):
    a = rest[i] 
    b = rest[i+1]
    c = rest[i+2]
Exemple #11
0
#!/usr/bin/python
import euler

isprime = euler.sieve(1000000)
primes = [x for x in range(1000000) if isprime[x]]

for run in range(1000, 20, -1):
    for start in range(len(primes) - run):
        v = sum(primes[start:start + run])
        if v >= 1000000:
            break
        if isprime[v]:
            print(run, v)
            exit(0)
Exemple #12
0
import euler

def tleft(n):
    seq = euler.intToSeq(n)
    return [ seq[:i] for i in range(1,len(seq)+1) ]

def tright(n):
    seq = euler.intToSeq(n)
    return [ seq[i:] for i in range(0,len(seq)) ]

def tall(n):
    return tleft(n) + tright(n)

res = []        
for n in euler.sieve(4000):
    if n > 7:
        seq = tall(n)
        seq = [ euler.seqToInt(x) for x in seq ]
        seq = [ euler.isprime(x) for x in seq ]
        val = reduce( lambda a,b : a and b, seq, True )
        if val:
            res.append(n)
            print n,seq

print 'soln',sum(res) + 739397
    #if sum([ 1 for x in seq if not euler.isprime(x) ]) == 0:
    #    print n
Exemple #13
0
import euler
import itertools

M = 10**6
primes = set(euler.sieve(M))

def check(c):
  for i in itertools.count(1):
    if 2 * i * i > c:
      return False
    p = c - 2 * i * i
    if p in primes:
      return True

for c in range(9, M, 2):
  if c in primes:
    continue
  if not check(c):
    print(c)
    break
Exemple #14
0
def main():
  maxPrime = 0
  for prime in sieve(7654321):
    if isPandigital(prime):
      maxPrime = prime
  print maxPrime
Created on Dec 26, 2016


The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, 
and, (ii) each of the 4-digit numbers are permutations of one another.
There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence.
What 12-digit number do you form by concatenating the three terms in this sequence?


@author: mstackpo
'''

from datetime import datetime
start = datetime.now()

from euler import sieve, is_prime
from itertools import permutations

n = 10000

for p in sieve(n):
    for y_string in permutations(str(p)):
        x = int(''.join(y_string))
        z = p + 2*(x-p)
        if p > 1000 and is_prime(x) and x > p and is_prime(z):
            my_perms = map( ''.join, permutations( str(p) ) )
            if str(z) in my_perms:
                print(p, x, z)                                      # Finds the answer twice for some reason

end = datetime.now()
print( "runtime = %s" % (end - start) )
Exemple #16
0
import euler
import math
import sys

N = 100000000

primes = list(euler.sieve(N))
primeset = set(primes)


def concat(p1, p2):
    pa = int(str(p1) + str(p2))
    pb = int(str(p2) + str(p1))
    return pa in primeset and pb in primeset


trie = [False, {}]
for p in primes:
    t = trie
    for c in map(int, str(p)):
        t = t[1].setdefault(c, [False, {}])
    t[0] = True


def iterprimes(trie, n=0):
    if trie[0]:
        yield (n, trie)
    for digit, ntrie in trie[1].items():
        yield from iterprimes(ntrie, n * 10 + digit)

Exemple #17
0
import euler

q1 = lambda x: (2 * x + 1)**2
q2 = lambda x: q1(x) - 2 * x
q3 = lambda x: q1(x) - 4 * x
q4 = lambda x: q1(x) - 6 * x

q = [q2, q3, q4]

maxprime = 14000
lowPrimes = euler.sieve(maxprime)
lowPrimes = set(lowPrimes)


def isprime(n):
    if n < maxprime:
        return n in lowPrimes
    else:
        #        return euler.isprime_slow(n)
        return euler.isprime(n)


@euler.in_mem_memoize
def nprimes(x):
    cnt = 0
    for qi in q:
        if isprime(qi(x)):
            cnt += 1
    return cnt

Exemple #18
0

def tleft(n):
    seq = euler.intToSeq(n)
    return [seq[:i] for i in range(1, len(seq) + 1)]


def tright(n):
    seq = euler.intToSeq(n)
    return [seq[i:] for i in range(0, len(seq))]


def tall(n):
    return tleft(n) + tright(n)


res = []
for n in euler.sieve(4000):
    if n > 7:
        seq = tall(n)
        seq = [euler.seqToInt(x) for x in seq]
        seq = [euler.isprime(x) for x in seq]
        val = reduce(lambda a, b: a and b, seq, True)
        if val:
            res.append(n)
            print n, seq

print 'soln', sum(res) + 739397
#if sum([ 1 for x in seq if not euler.isprime(x) ]) == 0:
#    print n
Exemple #19
0
import euler
import itertools

primes = list(euler.sieve(200))


def custom_partitions(n, elements, sol=[], index=0):
    if index >= len(elements):
        return
    for i in itertools.count(0):
        k = i * elements[index]
        if k > n:
            return
        next_sol = sol + [elements[index]] * i
        if k == n:
            yield next_sol
            return
        yield from custom_partitions(n - k, elements, next_sol, index + 1)


comp = lambda x: len(list(custom_partitions(x, primes))) < 5000
print(euler.first(itertools.dropwhile(comp, itertools.count(2))))
Exemple #20
0
import euler
import itertools

primes = set(euler.sieve(3 * 10**6))


def getmax(a, b):
    for n in itertools.count(0):
        if (n * n + a * n + b) not in primes:
            return n


ans = (0, 0, 0)
for a in range(-999, 1000):
    for b in range(-1000, 1001):
        current = (getmax(a, b), a, b)
        if ans[0] < current[0]:
            ans = current
            print(ans)
print(ans[1] * ans[2])
Exemple #21
0
##lst.sort()
##for i in lst:
##    print i
#
#v0 = 50000000
#v1 = 50
#
#print 4**10
#print v0
#print math.sqrt(v0)
#primes = euler.sieve( int(math.sqrt(v0)) +1 )
#print primes
#print len(primes)
#print len(primes)**3

v0 = 50000000
#v0 = 50
primes = euler.sieve( int(math.sqrt(v0)) +1 )

d = set()
tot = v0
for i in primes:
    itot = i**2
    for j in [ p for p in primes if p**3 < v0-itot ]:
        jtot = itot + j**3
        for k in [ p for p in primes if p**4 < v0-jtot ]:
            ktot = jtot + k**4
            print i,j,k,ktot
            d.add(ktot)
print len(d)
Exemple #22
0
import euler
import itertools

M = 1000000
primes = list(euler.sieve(M))
primeset = set(primes)


def intmask(mask):
    ans = 0
    for d in mask:
        ans = ans * 10 + d
    return ans


def candidates(base, imask, limit):
    for d in range(10):
        n = base + d * imask
        if limit <= n < 10 * limit:
            yield n in primeset


def itermasks(p):
    d = euler.digits(p)
    limit = 10**(d - 1)
    allmasks = itertools.product(range(2), repeat=d)
    for mask in itertools.islice(allmasks, 1, 2**d - 1):
        base = int("".join(
            (i if j == 0 else "0") for i, j in zip(str(p), mask)))
        imask = intmask(mask)
        yield (sum(candidates(base, imask, limit)), base, imask)
Exemple #23
0
def solution_2():
    primes = euler.sieve(2 * 10**6)
    Sum = 0
    for i in primes:
        Sum = Sum + i
    return Sum
Exemple #24
0
def main():
  sum = 0
  for i in euler.sieve(2000000):
    sum += i
  print sum
Exemple #25
0
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
Which prime, below one-million, can be written as the sum of the most consecutive primes?

@author: mstackpo
'''

from datetime import datetime
start = datetime.now()

from euler import is_prime, sieve

n = 4000
max_len = 0
max_total = 0

for p in sieve(n):
    total = p
    count = 1
    for x in sieve(n):
        if x > p:
            total += x
            count += 1
            if is_prime(total) and total < 1000000:
                if count > max_len:
                    max_len = count
                    max_total = total
                    print(max_total, max_len)

end = datetime.now()
print("runtime = %s" % (end - start))
Exemple #26
0
#!/usr/bin/python
import euler

primes = euler.sieve(10000)


def check_triple_gap(ps):
    for f in range(len(ps) - 2):
        for s in range(f + 1, len(ps) - 1):
            d = ps[s] - ps[f]
            if ps[s] + d in ps:
                print(ps[f], ps[s], ps[s] + d)
                return


def prime_perms(n):
    digits = euler.digits(n)
    return sorted(
        set(
            filter(lambda x: primes[x],
                   map(euler.num_from_digits, euler.perms(sorted(digits))))))


for n in range(1000, len(primes)):
    if not primes[n]:
        continue
    ps = prime_perms(n)
    if ps[0] != n:
        continue
    check_triple_gap(ps)
Exemple #27
0
import itertools
import euler
import math

M = 50 * 10**6
primes = list(euler.sieve(math.ceil(M**0.5)))


def primepower(power):
    for p in primes:
        yield p**power


ans = set()

L = M


def search(current, power):
    if power == 1:
        yield current
        return
    for p in itertools.takewhile(lambda p: current + p <= L,
                                 primepower(power)):
        yield from search(current + p, power - 1)


print(len(set(search(0, 4))))
Exemple #28
0
#!/usr/bin/python
import euler

Limit = 2000000

prime = euler.sieve(Limit)

sum = 0
for x in range(2, Limit):
    if (prime[x]):
        sum += x

print(sum)
Exemple #29
0
import euler
import collections
import sys

lst = euler.sieve(10000)
lst = [ i for i in lst if i >= 1000 ]
print len(lst)

def isPerm( a, b ):
    return set( euler.intToSeq(a) ) == set( euler.intToSeq(b) )


def seqPoints(seq):
    for i in range(len(seq)):
        for j in range(i+1,len(seq)):
            for k in range(j+1,len(seq)):
                yield [ seq[idx] for idx in [i,j,k] ]

def isArithmeticSeq(seq):
    for i in seqPoints(seq):
        a,b,c = tuple(i)
        if c-b == b-a:
            return True,str(a)+str(b)+str(c)
    return False,''

d = collections.defaultdict(set)
seen = set()
for i in lst:
    if i not in seen:
        for j in lst:
            if j not in seen and i != j and isPerm(i,j):
Exemple #30
0
def millionPrimes():
    lst = euler.sieve(1000000)
    return lst
import math
import euler
import time
def quad(n,a,b):
    return (n**2) + (a*n) + b
primes = euler.sieve(100000)
count = 0
max = 0
ans = 0
start = time.time()
for x in xrange(-999,0,2):
    for i in xrange(1,1000,2):
        while quad(count,x,i) in primes:
            count+=1
        if count > max:
            ans = x*i
            max = count
            print ans
        count = 0
print max, time.time()-start
The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, 
and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
Find the sum of the only eleven primes that are both truncatable from left to right and right to left.
NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.

@author: mstackpo
'''

from datetime import datetime

start = datetime.now()

import euler

p = 1000000
sieve = euler.sieve(p)
Sum = 0

for p in range(11, p):
    diff = p
    prime = True
    # Strip off digits from right and check for prime
    while (diff > 0 and prime):
        prime &= sieve[diff]
        diff //= 10
    # Strip of digits from left and check for prime
    diff = p
    while (diff > 0 and prime):
        prime &= sieve[diff]
        # convert to string to strip digit off right, special case if diff is single digit
        diff = int(str(diff)[1:]) if diff > 9 else 0
Exemple #33
0
import sys
sys.path.append("..")
from fraction import Fraction
from euler import sieve, digits

upper = 100
primes = sieve(upper)
valid = []

for den in range(10, upper):
    if den % 10 != 0:
        for num in range(10, den):
            q = Fraction(num, den)
            num_digits = digits(num, convert=True)
            den_digits = digits(den, convert=True)
            if len(set(num_digits) & set(den_digits)) == 1:
                same = (set(num_digits) & set(den_digits)).pop()
                num_digits.remove(same)
                den_digits.remove(same)
                num_fake = num_digits[0]
                den_fake = den_digits[0]
                fake = Fraction(num_fake, den_fake)
                if q == fake:
                    valid.append(q)

result = 1
for q in valid:
    result *= q.reduce()
print(result.reduce().denominator)

Exemple #34
0
def solution_2():
    primes = euler.sieve(2 * 10 ** 6)
    Sum = 0
    for i in primes:
        Sum = Sum + i
    return Sum