Ejemplo n.º 1
0
def truncatable_primes(limit=None):
    """Returns all truncatable primes up to limit, or optionally all 11."""
    # This is similar to the circular primes problem in that we can eliminate
    # a lot of primes that may have even numbers or 5s anywhere but the first
    # digit.
    primes = prime_sieve(limit) if limit else prime_sieve(1000000)
    digits = '024568'
    end_dg = '14689'
    primes = [x for x in primes if not any([d in str(x)[1:] for d in digits])]
    primes = [x for x in primes if not any([d in str(x)[0] for d in end_dg])]
    primes = [x for x in primes if not any([d in str(x)[-1] for d in end_dg])]
    primes = primes[4:]
    p_gen = prime_generator(1000000)
    trunc_primes = []

    i = 0
    while len(trunc_primes) < 11 and (i < len(primes) or not limit):
        try:
            p = str(primes[i])
        except IndexError:
            p = str(next(p_gen))
        for j in range(1, len(p)):
            if not is_prime(int(p[j:])) or not is_prime(int(p[:-j])):
                break
        else:
            trunc_primes.append(int(p))
        i += 1
    return trunc_primes
Ejemplo n.º 2
0
def circular_primes(limit):
    """Returns a list of circular primes up to limit."""

    # We can remove any prime that contains any even numbers and every prime
    # that contains a 5.

    if limit > 5:
        primes = prime_sieve(limit)[3:]
        digits = '024568'
        primes = [x for x in primes if not any([d in str(x) for d in digits])]
        primes = [2, 3, 5] + primes
    else:
        return [x for x in [2, 3, 5] if x <= limit]

    for i in range(len(primes)):
        p = str(primes[i])
        test = []
        for j in range(1, len(p)):
            if p == '0':
                break
            if int(p[j:] + p[:j]) not in primes:
                primes[i] = 0
                for fail in test:
                    primes[primes.index(fail)] = 0
                break
            else:
                test.append(int(p[j:] + p[:j]))
    return [x for x in primes if x != 0]
Ejemplo n.º 3
0
def main():
    # We're not going to worry about 2, 3, or 5--we can do that ourselves.
    primes = prime_sieve(17)[3:]
    pandigitals = pandigital_list(9, True)
    pandigitals = [x for x in pandigitals if str(x)[3] in '02468']  # 2
    pandigitals = [x for x in pandigitals if int(str(x)[2:5]) % 3 == 0]  # 3
    pandigitals = [x for x in pandigitals if str(x)[5] in '05']  # 5
    for i in range(len(primes)):
        p = primes[i]
        pandigitals = [
            x for x in pandigitals if int(str(x)[i + 4:i + 7]) % p == 0
        ]
    return sum(pandigitals)
Ejemplo n.º 4
0
def longest_repetend(n):
    d = prime_sieve(n)
    d.remove(2)
    d.remove(5)
    max_repetend = 0
    for number in d:
        x = 1
        while (10**x - 1) % number != 0:
            x += 1
        if x > max_repetend:
            max_repetend = x
            max_d = number
    return max_d
Ejemplo n.º 5
0
def longest_quadratic_primes(limit):
    b_list = prime_sieve(limit)  # Because f(0) = b, so b must be prime.
    # Further, when n = 1, p + 1 + even number will produce a non-prime. So a
    # must be odd. The only exception would be if b = 2, in which case if n = 2,
    # n² = 4 and a must again be odd to produce any more primes.
    a_list = [x for x in list(range(-limit + 1, limit)) if x % 2 == 1]
    max_length, max_a, max_b = 0, 0, 0
    for a in a_list:
        for b in b_list:
            n = 0
            while is_prime(n**2 + a * n + b):
                n += 1
            if n > max_length:
                max_length = n
                max_a = a
                max_b = b
    return (max_a, max_b)
Ejemplo n.º 6
0
def prime_concats(n):
    """
    Generates a dictionary of primes less than n with a list of other primes
    that, when concatenated together, also form a prime.
    """
    primes = prime_sieve(n)
    prime_dict = {}
    for i in range(len(primes)):
        p = primes[i]
        prime_dict[p] = []
        for q in primes[i + 1:]:
            if is_prime(int(str(p) + str(q))) and is_prime(
                    int(str(q) + str(p))):
                prime_dict[p].append(q)
    prime_concat_list = {}
    for p in prime_dict:
        if prime_dict[p] != []:
            prime_concat_list[p] = prime_dict[p]
    return prime_concat_list
Ejemplo n.º 7
0
def nth_prime(position):
    """Returns the nth prime number."""
    from math import log
    try:
        if int(position) != float(position):
            raise ValueError("number was not an integer.")
        elif int(position) < 1:
            raise ValueError("number was not positive.")
        else:
            position = int(position)
    except (TypeError, ValueError) as err:
        print("ERROR: argument must be a positive integer.")
        print("%s: %s" % (type(err).__name__, err))
        return
    small_primes = [2, 3, 5, 7, 11, 13, 17]
    if position < 8:
        return small_primes[position - 1]
    max_p = position * log(position)
    max_p += position * log(log(position))
    primes = prime_sieve(max_p)
    return primes[position - 1]
Ejemplo n.º 8
0
     2            1   1      2
     3          1,2   2     1.5
     4          1,3   2      2
     5      1,2,3,4   4     1.25
     6          1,5   2      3
     7  1,2,3,4,5,6   6    1.166
     8      1,3,5,7   4      2
     9  1,2,4,5,7,8   6     1.5
    10      1,3,7,9   4     2.5

It can be seen that n = 6 produces a maximum n/φ(n) for n ≤ 10.

Find the value of n ≤ 1,000,000 for which n/φ(n) is a maximum.
"""

from problem003 import prime_sieve

if __name__ == '__main__':
    # Euler's Totient Function is defined as n * ∏(1 - 1/p) where p are the
    # distinct primes of n.
    # The ratio n / φ(n) can thus be simplified to 1 / ∏(1 - 1/p), and
    # maximizes when the number of distinct primes is maximized.
    result = 1
    limit = 1000000
    primes = prime_sieve(200)
    for p in primes:
        result *= p
        if result > limit:
            print(result // p)
            break
Ejemplo n.º 9
0
"""
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all primes below two million.
"""

from problem003 import prime_sieve

if __name__ == '__main__':
    print(sum(prime_sieve(2000000)))
Ejemplo n.º 10
0
# denominator larger.
#
# We cannot use a prime itself since φ(p) = p - 1, and thus it cannot be a
# permutation of p. Instead, we should search for numbers with two large prime
# factors, p1 * p2, where p1 and p2 are close to √(10^7) ≈ 3162

from problem003 import prime_sieve
from itertools import combinations


def is_perm(n1, n2):
    return sorted(list(str(n1))) == sorted(list(str(n2)))


if __name__ == '__main__':
    primes = [p for p in prime_sieve(5000) if p > 2000]
    numbers = list(combinations(primes, 2))

    # Because φ(n) = n * (1 - 1/p1) * (1 - 1/p2), and n = p1 * p2, we can
    # simplify the Totient function to
    # φ(n) = p1 * p2 * (1 - 1/p1) * (1 - 1/p2) = (1 - p1) * (1 - p2)

    minimum = float('inf')
    for p in numbers:
        n = p[0] * p[1]
        if n > 10**7: continue
        T = (1 - p[0]) * (1 - p[1])
        if is_perm(n, T) and (n / T) < minimum:
            minimum = n / T
            answer = n
    print(answer)