Пример #1
0
def concatenating_primes():
    """
    Problem 60, recursive solution
    """

    primes = [str(i) for i in get_all_primes_under(10000)]

    @memo
    def mirror_str_test(a, b):
        ab = a + b
        if len(ab) > 5:
            if is_prime(int(ab)) and is_prime(int(b + a)):
                return True
        elif ab in primes and b + a in primes:
            return True
        return False

    def concatenate_recurse(primes, found=set()):
        if len(found) == 5:
            return found
        for i, a in enumerate(primes):
            if all(mirror_str_test(z, a) for z in found):
                result = concatenate_recurse(primes[i + 1 :], found | {a})
                if result:
                    return result
        return False

    return concatenate_recurse(primes)
Пример #2
0
def prime_permutations():
    """
    finds all primes (necessarily 4 digit primes) that are in an arithmetic sequence and in which each is a permutation of the other
    problem 49
    """
    all_primes = get_all_primes_under(10000)
    four_digit_primes = all_primes[all_primes.index(min(all_primes, key=lambda x: abs(x - 1000))) :]
    groups = []
    possibilities = dict(zip(four_digit_primes, [False] * len(four_digit_primes)))
    for p, v in possibilities.items():
        if v == True:
            continue
        perms = {int("".join(i)) for i in itertools.permutations(str(p))}
        overlap = []
        for k in perms:
            if k in possibilities.keys():
                possibilities[k] = True
                overlap.append(k)
        if len(overlap) >= 3:
            groups.append(tuple(sorted(overlap)))

    prime_permutations = set()
    for g in groups:
        for j in itertools.permutations(g, 3):
            j = sorted(j)
            if is_arithmetic_sequence(j[0], j[1], j[2]):
                prime_permutations.add(tuple(j))
    return prime_permutations
Пример #3
0
def number_of_prime_factors(maximum):
    primes = get_all_primes_under(maximum // 2)
    count = 0
    last_index = len(primes) - 1
    for i, p in enumerate(primes):
        while primes[last_index] * p > maximum:
            if i > last_index:
                return count  # square of prime at i still be in bounds
            last_index -= 1
        count += last_index - i + 1
Пример #4
0
def alternate_prime_sum():
    ps=get_all_primes_under(3946)
    mt,ms,mcps=len(ps),sum(ps),(0,0)
    while mt>mcps[0]:
        ls=ms if ms%2 else ms-1
        while not is_prime(ls): ls-=2
        k,ts=0,ms
        while ts-ls>0: ts-=ps[k]; k+=1
        if ts==ls and mt-k>mcps[0]: mcps=(mt-k,ts)
        mt-=1
        ms-=ps[mt]

    print(mcps)
Пример #5
0
def eul50():
    primes = get_all_primes_under(10**6)
    d = {}
    running = 0
    for p in primes:
        if p > 50000: break
        running += p
        d[p] = running
    b = sorted(d.keys())
    best = (21, 953)
    e = {}
    for i in range(len(b)):
        for j in range(i + (best[0] if best[0]%2 == 1 else best[0]-1), len(b)-1, 2):
            val = d[b[j]] - d[b[i]]
            if val > 1000000: break
            if val in primes and j-i > best[0]: best=(j-i, val)
    return best
Пример #6
0
def prime_digit_replacements(target = 7):
    '''
    find the lowest prime having a repeated digit that can be
    replaced by other digits and thereby create other primes in the 'family'
    problem 51
    '''
    wildcard = 'a'
    primes = get_all_primes_under(10**7)[5700:] #between 10**8 and 10**7
    primes = [(p,c) for (p,c) in [(p,Counter(p)) for p in [str(p) for p in primes]] if len(p) >= len(c) + 2]
    stripped = []
    for p,c in primes:
        for char in [e for e,v in c.items() if v == 3]:
            stripped.append((p.replace(char,wildcard),p))
        for char in [e for e,v in c.items() if v > 3]:
            for (a,b,c) in itertools.combinations([ind for ind,r_char in enumerate(p) if char == r_char],3):
                q = list(p)
                q[a],q[b],q[c] = wildcard,wildcard,wildcard
                stripped.append((''.join(q),p))
    stripped.sort()
    return stripped
Пример #7
0
def concatenating_primes():
    """
    problem 60
    """
    primes = [str(p) for p in get_all_primes_under(10000)]
    parts = collections.defaultdict(set)

    def mirror_str_test(a, b):
        ab = a + b
        if len(ab) > 5:
            if is_prime(int(ab)) and is_prime(int(b + a)):
                return True
        elif ab in primes and b + a in primes:
            return True
        return False

    def concatenate_recurse(primes, found={}):
        if len(found) == 5:
            return found
        for i, a in enumerate(primes):
            if all(mirror_str_test(z, a) for z in found):
                result = concatenate_recurse(primes, found & a)
                if result:
                    return result
        return False

    for i, a in enumerate(primes):
        found = {a}
        for j, b in enumerate(primes[i + 1 :]):
            if all(mirror_str_test(z, b) for z in found):
                found = {a, b}
                for k, c in enumerate(primes[j + 1 :]):
                    if all(mirror_str_test(z, c) for z in found):
                        found = {a, b, c}
                        for l, d in enumerate(primes[k + 1 :]):
                            if all(mirror_str_test(z, d) for z in found):
                                found = {a, b, c, d}
                                for e in primes[l + 1 :]:
                                    if all(mirror_str_test(z, e) for z in found):
                                        return {a, b, c, d, e}
    return "F**K"
Пример #8
0
def consecutive_prime_sum(lim = 1000):
    '''
    find the longest sequence of primes summing to a prime beneath lim
    problem 50
    '''
    all_primes = get_all_primes_under(lim)
    longest = {'length':2,'sum':5}
    min_sum = 5
    while longest['length'] < len(all_primes):
        p = all_primes.pop()
        if p < min_sum:
            print('hit min sum ',min_sum)
            break
        med = int(p/2)
        b = min(range(len(all_primes)), key=lambda i: abs(all_primes[i]-med))
        a = b-1
        value = sum(all_primes[a:b+1])
        primes_underneath = sum(all_primes[:a])
        while a > 0:
            if value > p:
                value -= all_primes[b]
                b -= 1
                a -= 1
                value += all_primes[a]
                primes_underneath -= all_primes[a]
            elif value < p:
                if primes_underneath < p-value:
                    break
                a -= 1
                value += all_primes[a]
                primes_underneath -= all_primes[a]
            else:
                length = b-a+1
                if length > longest['length']:
                    longest['length'],longest['sum'] = length,value
                    min_sum = sum(all_primes[:longest['length']])
                value -= all_primes[b]
                b -= 1
    return longest
Пример #9
0
def quadratic_prime_with_a_and_b_under(maximum):
    '''
    returns a list of tuple (a,b) from 'n^2 + an + b' and an integer
    representing how effective that quad is at predicting primes for
    consecutive n values.

    b must be a prime (0 + 0a + b) if at all effective, and a+b+1 must
    be a prime to get 2

    problem 27
    '''
    primes_under_max = get_all_primes_under(maximum)
    products = itertools.product(range(-maximum,maximum+1),primes_under_max)
    terms = {(a,b):2 for (a,b) in products if a+b+1 in primes_under_max or is_prime(a+b+1)}
    for (a,b),num in terms.items():
        n = 2
        q = get_quadratic(n,a,b)
        while q in primes_under_max if q < maximum else is_prime(q):
            n += 1
            q = get_quadratic(n,a,b)

        terms[(a,b)] = n-1
    return terms
Пример #10
0
def permuted_totients(limit=10**7):
    '''
    problem 70 -- find the permuted number-totient pair for which n/phi(n) is a minimum
    '''
    rooted = int((limit)**.5)
    primes = get_all_primes_under(rooted*3)
    mid_index = primes.index(min(primes,key=lambda x:abs(x-rooted)))
    step = mid_index//10
    best_n_phi, found, i, cache = limit, (0,0,0), 0, set()
    while found == (0,0,0) and i < mid_index:
        i += step
        for p in primes[mid_index:mid_index+i]:
            for q in primes[mid_index:mid_index-i:-1]:
                n = p*q
                if n > limit or n in cache: continue
                cache.add(n)
                phi = (p-1)*(q-1)
                n_over_phi = n/phi
                if n_over_phi > best_n_phi: break
                sn,sphi = str(n),str(phi)
                if sorted(sn) == sorted(sphi):
                    best_n_phi,found = n_over_phi,(n,p,q)
                    break #if we find one here, we won't find any better totient ratios below, so stop looking
    return found
Пример #11
0
from problem_10 import get_all_primes_under
from itertools import islice


primes = get_all_primes_under(10**6)


def get_square_prime_remainder(p, n):
    return ((p - 1)**n + (p + 1)**n) % p**2


def prime_square_remainder(limit):
    for i, prime in islice(enumerate(primes), 7034, None, 2):
        r = get_square_prime_remainder(prime, i + 1)
        if r > limit:
            return i + 1


if __name__ == '__main__':
    print prime_square_remainder(10**10)