Exemple #1
0
def main(verbose=False):
    prime_max = 10 ** 5
    PRIMES = sieve(prime_max)
    found = []
    n = 2
    while len(found) < 25:
        n += 1
        if n > prime_max:
            prime_max *= 10
            PRIMES = sieve(prime_max)

        if n % 2 == 0 or n % 5 == 0 or n in PRIMES:
            continue

        basis = n
        if n % 3 == 0:
            basis = 9 * n

        if (n - 1) % order_mod_n(10, basis) == 0:
            found.append(n)
    if verbose:
        return ('%s.\nAs a check, the first five values are calculated to be '
                '%s, as stated.' % (sum(found),
                                    ', '.join(str(num) for num in found[:5])))
    else:
        return sum(found)
Exemple #2
0
def main(verbose=False):
    PRIMES = sieve(10 ** 5)
    running_sum = 0
    for prime in PRIMES:
        if not prime_divides_repunit_power10(prime):
            running_sum += prime
    return running_sum
Exemple #3
0
def main(verbose=False):
    prime_factors_hash = {}

    MINIMUM_SOLUTIONS = 4*(10**6)
    # P^k < 10**7 (10 mil)
    powers = [power_up_to_digits(prime, 7)
              for prime in [3, 5, 7]]
    products = [reduce(operator.mul, triple) for
                triple in list(i_product(*powers))]
    products = [product for product in sorted(products)
                if product > 2*MINIMUM_SOLUTIONS][:20]

    PRIMES = sieve(100)

    max_prod = 10**21
    res = []
    for product in products:
        factors = prime_factors(product, unique=False, hash_=prime_factors_hash)
        factors = [(factor - 1)/2 for factor in factors][::-1]
        curr_prod = 1
        for i, exp in enumerate(factors):
            curr_prod = curr_prod*(PRIMES[i]**exp)

        if curr_prod < max_prod:
            max_prod = curr_prod

    return max_prod
Exemple #4
0
def main(verbose=False):
    # layer/primes
    #     2/3
    #  1581/835
    #  3536/1677
    #  5000/2249
    # 13121/5248, winning layer

    # ratio >= .1 iff 10*(primes/total) >= 1 iff 10*primes >= total
    # iff 10*primes >= 4*index - 3
    FAILURE_POINT = 10 ** 9
    PRIMES = sieve(int(sqrt(FAILURE_POINT)) + 1)

    layer = 2
    num_primes = 3
    while 10 * num_primes >= 4 * layer - 3:
        layer += 1
        candidates = [(2 * layer - 1) ** 2 - 2 * (layer - 1) * i
                      for i in range(1, 4)]
        if candidates[-1] >= FAILURE_POINT:
            raise ValueError("Sieve was not big enough, restart function")
        for candidate in candidates:
            if is_prime(candidate, primes=PRIMES, failure_point=FAILURE_POINT):
                num_primes += 1
    side_length = 2 * layer - 1  # 2*(layer - 1) + 1
    return side_length
Exemple #5
0
def main(verbose=False):
    PRIMES = sieve(10 ** 7)
    running_sum = 0
    for prime in PRIMES:
        if prime not in [2, 5]:
            running_sum += inverse_mod_n(10, prime)
    return running_sum
Exemple #6
0
def main(verbose=False):
    primes = sieve(100)

    MAX_n = 10 ** 16

    product_factor_pairs = [(1, 0)]
    product_hash = {0: [1]}
    for num_factors in range(1, 13 + 1):
        product_hash[num_factors] = []

    # (1,0) becomes
    # (1,0), (p, 1) becomes
    # (1,0), (p, 1), (q,1), (q*p, 2) etc.
    for prime in primes:
        to_add = []
        for product, num_factors in product_factor_pairs:
            if prime * product < MAX_n:
                to_add.append((prime * product, num_factors + 1))
                product_hash[num_factors + 1].append(prime * product)
        product_factor_pairs += to_add

    result = 0
    sign = -1
    for num_factors in range(4, 13 + 1):
        sign = -sign
        PIE_factor = sign * choose(num_factors - 1, 3)
        current_sum = 0
        for product in product_hash[num_factors]:
            current_sum += MAX_n / product  # integer division
        result += PIE_factor * current_sum

    return result
Exemple #7
0
def all_circular(n):
    # the number of digits limits the size of all permutations
    digs = len(str(n))
    possible_primes = [2, 5] + \
        [prime for prime in sieve(10**digs - 1)
         if contains_only_digits(prime, [1, 3, 7, 9])]
    return [prime for prime in possible_primes if prime <= n
             and all_circular_perm_in(prime, possible_primes)]
Exemple #8
0
def main(verbose=False):
    # By the prime number theorem, pi(x) =~ x/ln(x)
    # pi(x) >= 10001 when x >= 10001 ln(x)
    # To be safe, we'll double it and solve
    # x = 20002 ln(x)

    # We are left with approximately 248490
    primes = sieve(248490)
    return primes[10001 - 1]
Exemple #9
0
def main(verbose=False):
    # sieve(6000) will do it (answer is 5777)
    curr = 9
    primes = sieve(5777)
    while is_possible(curr, primes):
        curr += 2
        while curr in primes:
            curr += 2
    return curr
Exemple #10
0
def main(verbose=False):
    problem_max = 10 ** 6
    count = 0
    PRIMES = sieve(problem_max)
    max_L = int(round((sqrt(12 * problem_max - 3) - 3) / 6))
    for L in xrange(1, max_L + 1):
        difference = (L + 1) ** 3 - L ** 3
        if difference in PRIMES:
            count += 1
    return count
Exemple #11
0
def prime_sequence_exists(length, digits, primes=[]):
    """
    Returns True if a sequence of length consecutive primes which sums
    to less than 10**digits also sums to a prime number
    """
    cap = 10**digits
    if primes == []:
        primes = sieve(cap)
    sums = [sum(seq) for seq in all_prime_seqs(length, digits, primes)]
    return (set(sums).intersection(primes) != set())
Exemple #12
0
def main(verbose=False):
    problem_max = 10 ** 6
    PRIMES = sieve(problem_max)
    # ignore zero index
    ratios = [(1, index) for index in range(problem_max + 1)]
    for prime in PRIMES:
        ratios[prime::prime] = [((ratio * prime * 1.0) / (prime - 1), index)
                                for ratio, index in ratios[prime::prime]]
    ratios.sort(key=lambda pair: pair[0], reverse=True)
    return ratios[0][1]
Exemple #13
0
def matches(problem_max):
    PRIMES = sieve(problem_max)
    phi_list = range(problem_max + 1)  # ignore zero index
    for prime in PRIMES:
        phi_list[prime::prime] = [(val / prime) * (prime - 1) for val in
                                  phi_list[prime::prime]]
    cands = [(val, phi_list[val]) for val in range(2, problem_max + 1)
             if same_digits(val, phi_list[val])]
    cands.sort(key=lambda cand: (cand[0] * 1.0) / cand[1])
    return cands[0][0]
Exemple #14
0
def main(verbose=False):
    PRIMES = sieve(10 ** 6)
    prime_index = 3  # p0=2, p1=3, and p2=5 are false positives
    matches = []
    while len(matches) < 40:
        prime = PRIMES[prime_index]
        if prime_divides_repunit_power10(prime, 9):
            matches.append(prime)
        prime_index += 1

    return sum(matches)
Exemple #15
0
def main(verbose=False):
    # Since p_n > 70710, to be safe let's multiply by 10
    PRIMES = sieve(707100)
    # The odd primes are the even indices here
    prime_index = 1
    product = 2*(1*2) # p_1 = 2
    while product < 10**10:
        prime_index += 2
        prime = PRIMES[prime_index-1]
        product = 2*(prime_index*prime)
    return prime_index
Exemple #16
0
def all_radicals(n):
    PRIMES = sieve(n)
    result = {1: 1}
    for i in range(2, n + 1):
        if i in PRIMES:
            result[i] = i
        prime, quotient = first_prime_divisor(i, PRIMES)
        if quotient % prime == 0:
            result[i] = result[quotient]
        else:
            result[i] = result[quotient]*prime
    return result
Exemple #17
0
def main(verbose=False):
    PRIMES = sieve(10 ** 6 + 3)  # 10**6 + 3 is the final value of p_2

    running_sum = 0
    for index in range(2, len(PRIMES) - 1):
        p_1 = PRIMES[index]
        p_2 = PRIMES[index + 1]
        ten_inverse = inverse_mod_n(10, p_2)
        digits = len(str(p_1))
        k = (ten_inverse ** digits) * (p_2 - p_1) % p_2
        running_sum += int('%s%s' % (k, p_1))
    return running_sum
Exemple #18
0
def longest_prime_sequence(digits, primes=[]):
    """
    Returns the length of the most consecutive primes which sum
    to a prime and sum to less then 10**digits
    """
    if primes == []:
        primes = sieve(10**digits)
    max_length = max_prime_length(digits, primes)
    for length in range(max_length, 0, -1):
        if prime_sequence_exists(length, digits, primes):
            return length
    raise ValueError("Algorithm failed")
Exemple #19
0
def main(verbose=False):
    MAX_n = 10 ** 6 - 1
    distinct_solutions = 10
    PRIMES = sieve(int(sqrt(MAX_n)) + 1)
    factor_hash = {}

    count = 0
    for n in range(1, MAX_n + 1):
        factor_list = factors(n, factor_hash, PRIMES)
        if len(num_solutions(factor_list)) == distinct_solutions:
            count += 1
    return count
Exemple #20
0
def main(verbose=False):
    MAX_n = 987654321
    PRIMES = sieve(int(sqrt(MAX_n)))
    # A 9 digit pandigital will have digit sum 45, so can't be prime
    # must be divisible by 9
    for i in range(8, 1, -1):
        cand = [str(dig) for dig in range(1, i + 1)]
        cand = int("".join(cand))
        candidates = sorted(all_permutations_digits(cand))[::-1]
        for candidate in candidates:
            if is_prime(candidate, primes=PRIMES, failure_point=MAX_n):
                return candidate
    raise ValueError("No prime was found, algorithm busted.")
Exemple #21
0
def main(verbose=False):
    D = 10 ** 6
    PRIMES = sieve(int(sqrt(D)) + 1)
    # We seek |F_D| = 1 + sum_{i in  1 to D} PHI(i)
    # 2*sum_{i in  1 to D} PHI(i) = 1 + sum_{i in  1 to D} MU(i) floor(D/i)**2
    # 2*|F_D| = 3 + sum_{i in  1 to D} MU(i) floor(D/i)**2
    mu_hash = {1: 1}
    running_sum = D ** 2  # i = 1
    for i in range(2, D + 1):
        running_sum += mu(i, mu_hash, PRIMES) * (int(floor(D * 1.0 / i)) ** 2)

    # They don't include 0/1 or 1/1 so we subtract 2
    return ((3 + running_sum) / 2 - 2)
Exemple #22
0
def find_first_n_truncatable(n, max_n):
    result = []
    primes = sieve(max_n)[4:] # We don't include 2, 3, 5, or 7
    for prime in primes:
        if is_truncatable_prime(prime, primes):
            result.append(prime)
        if len(result) == n:
            return result

    if len(result) < n:
        raise Exception("Not enough found, raise max_n")

    return result
Exemple #23
0
def main(verbose=False):
    PRIMES = sieve(10 ** 6)

    for prime in PRIMES:
        digit, count = most_common_digit(prime)
        if count > 2:
            candidates = find_and_replace(prime, digit)
            match_count = 0
            for candidate in candidates:
                if candidate in PRIMES:
                    match_count += 1
            if match_count == 8:
                return prime
Exemple #24
0
def main(verbose=False):
    MAX_n = 10 ** 8
    # q <= p, q**2 <= pq = n < max_n, q < sqrt(max_n)
    # 2 <= q, 2p <= pq < max_n, p < max_n/2
    # Given q, pq < max_n, p < max_n/q
    PRIMES = sieve(MAX_n / 2)  # integer division intended
    result = 0
    q_max_index = bisect(PRIMES, sqrt(MAX_n))
    for q_index in range(q_max_index + 1):
        p_min_index = q_index
        p_max_index = bisect(PRIMES, MAX_n * 1.0 / PRIMES[q_index])
        result += p_max_index - p_min_index
    return result
Exemple #25
0
def relevant_triples(n):
    result = []
    top_sieve = sieve(max_p(2, n))
    next3 = [prime for prime in top_sieve
             if prime <= max_p(4, n)]
    for p3 in next3:
        next2 = [prime for prime in top_sieve
                 if prime <= max_p(3, n - p3 ** 4)]
        for p2 in next2:
            next1 = [prime for prime in top_sieve
                     if prime <= max_p(2, n - p3 ** 4 - p2 ** 3)]
            for p1 in next1:
                if p1 ** 2 + p2 ** 3 + p3 ** 4 < n:
                    result.append(p1 ** 2 + p2 ** 3 + p3 ** 4)
    return set(result)
Exemple #26
0
def main(verbose=False):
    primes = [prime for prime in sieve(10000) if prime > 999]
    primes_by_digits = {}
    for prime in primes:
        key = "".join(sorted(digit for digit in str(prime)))
        # sets value to [] if not set, returns value at key
        primes_by_digits.setdefault(key, []).append(prime)

    result = []
    for key in primes_by_digits:
        candidate = primes_by_digits[key]
        if len(candidate) >= 3:
            soln = find_arithmetic(candidate)
            if soln:
                result.append("".join(str(num) for num in sorted(soln)))
    return result[0]
Exemple #27
0
def max_prime_length(digits, primes=[]):
    """
    Returns the length of the longest string of primes
    (starting at 2,3,5,...) that will sum to less 10**digits
    """
    cap = 10**digits
    if primes == []:
        primes = sieve(int(4 * sqrt(cap)))
    count = 0
    num_primes = 0
    for prime in primes:
        if count + prime < cap:
            count += prime
            num_primes += 1
        else:
            return num_primes
    raise ValueError("max_prime_length failed logic.")
Exemple #28
0
def main(verbose=False):
    PRIMES = sieve(86238)
    b_choices = [prime for prime in PRIMES if prime < 1000]

    candidates = [(a, b, polynomial_consecutive_primes(a, b, PRIMES))
                  for a in range(-999, 999 + 1)
                  for b in b_choices]
    quantities = [entry[2] for entry in candidates]
    winner = candidates[quantities.index(max(quantities))]
    prod = winner[0]*winner[1]
    a = winner[0]
    b = winner[1]
    max_vals = winner[2]

    if verbose:
        return ('%s.\nSetting a = %s and b = %s produces '
                '%s consecutive primes.' % (prod, a, b, max_vals))
    else:
        return prod
Exemple #29
0
def main(verbose=False):
    MAX_n = 10 ** 4
    PRIMES = sieve(MAX_n)
    partner_hash = prime_concat_partners(PRIMES, PRIMES, MAX_n ** 2)
    valid = possible_pairings(partner_hash, 5)

    min_sum = 10 ** 10
    min_set = None
    for subset in valid:
        if sum(subset) < min_sum:
            min_sum = sum(subset)
            min_set = subset

    min_set = [str(prime) for prime in sorted(min_set)]
    if verbose:
        return '%s.\nThis is obtained with the primes %s.' % (
            min_sum, ', '.join(min_set))
    else:
        return min_sum
Exemple #30
0
def main(verbose=False):
    TOTAL = 2000
    MAX_n = 10 ** 6
    PRIMES = sieve(MAX_n)
    # Constant, rather than linear lookup
    prime_bools = [False] * (MAX_n + 1)
    for prime in PRIMES:
        prime_bools[prime] = True

    count = 2
    current = 2

    layer = 3
    first_corner = 8  # Value of first corner in layer
    last_corner = 19  # Value of last corner in layer
    six_shared = 11  # prime candidate shared by both corners,
    # with a difference of 6
    six_first = 13  # prime candidate for first corner, diff 6
    six_last = 17  # prime candidate for last corner, diff 6
    twelve_first = 29  # prime candidate for first corner, diff 12
    twelve_last = 17  # prime candidate for last corner, diff 12
    while count < TOTAL:
        if twelve_first > MAX_n:
            raise Exception("Primes not large enough")
        if prime_bools[six_shared]:
            if prime_bools[six_first] and prime_bools[twelve_first]:
                current = first_corner
                count += 1
            if count < TOTAL:
                if prime_bools[six_last] and prime_bools[twelve_last]:
                    current = last_corner
                    count += 1

        six_shared, six_last = six_last, six_last + 6
        six_first += 6
        twelve_last, twelve_first = twelve_first, twelve_first + 12

        first_corner += 6 * (layer - 1)
        last_corner += 6 * layer

        layer += 1

    return current