Exemplo n.º 1
0
def sum_truncatable_primes(n, r, i=4, t=[]):
    primes = prime_sieve(r)
    while len(t) < n:
        if truncatable_prime(primes[i]):
            t.append(primes[i])
        i += 1
    return sum(t)
Exemplo n.º 2
0
def problem_69(r, m=1):
    # find the product of consecutive primes under r
    primes = prime_sieve(50)
    for x in primes:
        if m * x > r:
            return m
        m *= x
Exemplo n.º 3
0
def compute():
    limit = 10 ** 6
    primes = prime_sieve(limit)
    n = 7035
    while (2 * n * primes[n-2]) % (primes[n-2] ** 2) < 10 ** 10 and n < limit:
        n += 1
    return n
Exemplo n.º 4
0
def get_n_digit_primes(n):
    prime_list = []
    for i in prime_sieve(10**n):
        if num_digits(i) == n:
            prime_list.append(i)

    return prime_list
Exemplo n.º 5
0
def compute():
    target = 5000
    values = list(prime_sieve(target))
    i = 2
    while ways_to_sum(i, values) <= target:
        i += 1
    return i
Exemplo n.º 6
0
def compute():
    candidates =  list(prime_sieve(7654321))
    ''' Pandigital numbers with 8 or 9 digits are always divisible by 3
    so the solution can have at most 7 digits
    '''
    for i in range(len(candidates)-1,1,-1):
        n = candidates[i]
        if is_pandigital(n):
            return n
Exemplo n.º 7
0
def compute():
    limit = 10 ** 8
    primes = prime_sieve(limit / 2 + 1)
    primes_iter = [p for p in primes if p ** 2 < limit]

    count = 0
    for i in primes_iter:
        primes = [p for p in primes if i * p < limit and p >= i]
        count += len(primes)

    return count
Exemplo n.º 8
0
def compute():
    limit = 10000
    primes = prime_sieve(limit)
    squares = [2 * j**2 for j in range(int(limit**0.5))]
    S = set(range(3, limit, 2)) - set(primes)
    for p in primes:
        for s in squares:
            S.discard(s+p)
    if len(S) == 0:
        return -1
    else:
        return min(S)
Exemplo n.º 9
0
def generate_list(primes, limit):
    result = []
    for i, val in enumerate(primes):
        higher_primes = [k for k in prime_sieve(limit) if k > max(val)]
        for j in higher_primes:
            if p060(val, j):
                s_list = []  # list of successful pairings
                [s_list.append(l) for l in val]
                s_list.append(j)
                result.append(s_list)

    return result
Exemplo n.º 10
0
def compute():
    composites = set(range(6, 10**6)) - set(prime_sieve(10**6))
    count = 0
    ans = 0
    for c in composites:
        if gcd(c, 10) == 1:
            if (c-1) % A(c) == 0:
                ans += c
                count += 1
                if count == 25:
                    break

    return ans
Exemplo n.º 11
0
def get_answer():
    '''  '''
    max_value = 10**8

    # get all prime factors that could be 2 factor
    primes = sorted(euler.prime_sieve(max_value/2 + 10**6))
    two_factor_count, max_index = 0, len(primes)

    for i, prime0 in enumerate(primes):
        limit = 10**8 / prime0;
        j = i
        while j <= max_index and primes[j] <= limit:
            two_factor_count += 1
            j += 1
    print 'two_factor_count: {}'.format(two_factor_count)
Exemplo n.º 12
0
def compute():
    i = 647
    limit = 1000000
    run = 0
    i_run = 0
    primes = set(prime_sieve(limit))

    while run < 4:
        factors = list_divisors(i)
        factors = [f for f in factors if (f % 2 == 1 or f == 2) and f in primes]
        if len(factors) == 4:
            if run == 0:
                i_run = i
            run += 1
        else:
            run = 0
        i += 1
    return i_run
Exemplo n.º 13
0
def compute():
    limit = 50 * 10**6
    primes_2 = list(prime_sieve(int(limit**0.5)))
    primes_3 = list(filter(lambda x: x < limit**(1.0 / 3.0), primes_2))
    primes_4 = list(filter(lambda x: x < limit**(1.0 / 4.0), primes_2))

    sums_2 = sorted([primes_2[i]**2 for i in range(len(primes_2))])
    sums_34 = sorted([primes_3[i]**3 + primes_4[j]**4 for i in range(len(primes_3)) for j in range(len(primes_4))])

    sums = set()
    for i in range(len(sums_34)):
        for j in range(len(primes_2)):
            temp = sums_2[j] + sums_34[i]
            if temp >= limit:
                break
            sums.add(temp)

    return len(sums)
Exemplo n.º 14
0
def compute():
    def find_arithmetic_sequence(L):
        L.sort()
        for i in range(len(L)):
            for j in range(i + 1,len(L)):
                for k in range(j + 1, len(L)):
                    if L[k] - L[j] == L[j] - L[i]:
                        return [L[i], L[j], L[k]]
        return -1

    primes = set(prime_sieve(10000)) - set(range(1000)) - {1487, 4817, 841}
    primes_lookup = {}

    for p in primes:
        key = int("".join(sorted(list(str(p)))))
        if key in primes_lookup:
            primes_lookup[key].append(p)
        else:
            primes_lookup[key] = [p]

    candidates = [x for x in list(primes_lookup.values()) if len(x) > 2]
    return [find_arithmetic_sequence(L) for L in candidates if find_arithmetic_sequence(L) != -1][0]
Exemplo n.º 15
0
# https://projecteuler.net/problem=50

from euler import prime_sieve, is_prime
from time import time
T = time()

limit = 1000000
primes = []
for i in prime_sieve(limit):
    primes.append(i)

# first find upper bound of consecutive primes:
running_sum = 0
upper_bound = 0
for i, val in enumerate(primes):
    running_sum += val
    if running_sum > limit:
        upper_bound = i  # the upper bound on number of consecutive primes given a limit
        break

# start with the upper bound and remove one prime at a time
sum_of_primes = 0
largest_jump = 0
largest_prime = 2
for i in range(0, len(primes)):
    for j in range(upper_bound, 1, -1):
        sum_of_primes = sum(primes[i:j])
        if is_prime(sum_of_primes) and largest_jump < j-i:
            largest_jump = j-i
            largest_prime = sum_of_primes
            break
Exemplo n.º 16
0
# coding=utf-8

'''
Problem 49
01 August 2003

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?
'''

import euler, collections, itertools, math
prime_sets = collections.defaultdict(list)
for prime in euler.prime_sieve(10**4):
  if (prime > 1000):
    key = tuple(sorted(str(prime)))
    prime_sets[key].append(prime)
for prime_set in prime_sets.itervalues():
  if (len(prime_set) >= 3):
    for pset in itertools.permutations(prime_set, 3):
      if (pset[2]-pset[1] == pset[1]-pset[0]) and (pset[0] < pset[1]):
        print ''.join(str(i) for i in pset)
Exemplo n.º 17
0
def compute():
    return sum(prime_sieve(2000000))
Exemplo n.º 18
0
Arquivo: 10.py Projeto: higgsd/euler
# 142913828922
import euler
N = 2000000
sieve = euler.prime_sieve(N)
print sum([p for p in xrange(N) if sieve[p]])
Exemplo n.º 19
0
# coding=utf-8
'''
Problem 37
14 February 2003

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.
'''

import euler


def truncatable_prime(n):
    if n < 10: return False
    for i in range(1, len(str(n))):
        if not euler.is_prime(int(str(n)[i:])) or not euler.is_prime(
                int(str(n)[:-i])):
            return False
    return True


print sum(i for i in euler.prime_sieve(10**6) if truncatable_prime(i))
Exemplo n.º 20
0
import euler

prime_list = [x for x in euler.prime_sieve(1000000)]

def rotate_left(num):
    num = str(num)
    first_digit = num[0]
    return num[1:] + first_digit

#euler.is_prime(rotate_left(prime))
def check_prime(num):
    length = len(str(num))
    inc = 1
    while inc < length:
        num = rotate_left(num)
        if not euler.is_prime(int(num)):
            return False
        inc += 1
  #  print num
    return True
        
answer = []    
count = 0
for prime in prime_list:
    if check_prime(prime):
        count += 1
        answer.append(prime)
print count
print answer
    
Exemplo n.º 21
0
from euler import prime_sieve, multiply_polynomials

primes = prime_sieve(10000)

for i in range(12,500):
    result = map(lambda x:int(x%2==0),[j for j in range(i+1)])
    for j in primes:
        if j > i:
            
            break
        elif j == 2:
            continue
        else:
            tmp = map(lambda x:int(x%j==0),[k for k in range(i+1)])
            result = multiply_polynomials(result,tmp)
    if result[i] > 5000:
        print "%d can be written as the sum of primes in %d ways" % (i, result[i])
Exemplo n.º 22
0
import euler

# using fermats theorem
primes = list(euler.prime_sieve(1000))


def cycle_length(d):
    cyc_len = None
    n = 0
    while cyc_len is None and n < d:
        n += 1
        if pow(10, n, d) == 1:
            cyc_len = n
    return (n)


max_cycle = 0
max_d = 0
for d in reversed(primes):
    cyc = cycle_length(d)
    if max_cycle < cyc:
        max_cycle = cyc
        max_d = d
    if max_cycle > d:
        break
print(max_d)
print(max_cycle)
Exemplo n.º 23
0
#!/usr/bin/python -tt
'''
  problem 111: http://projecteuler.net/problem=111
'''

from euler import prime_sieve

max_prime = 10**(4)
p = prime_sieve(max_prime)
Exemplo n.º 24
0
# brute force:
max_value = 0
max_value_num = 2
for num in range(2, 10**6+1):
    n_div_phi = num/phi(num)
    if n_div_phi > max_value:
        max_value = n_div_phi
        max_value_num = num

print(max_value_num)
print("time elapsed:", time() - T)

"""
Pen and paper method:
Notice that n/phi(n) = 1/((1-1/p1)*(1-1/p2)...)
Hence n/phi(n) is maximal when ((1-1/p1)*(1-1/p2)...) is minimal
This happens using the smallest primes, so we simply multiply the
smallest primes together and make sure we stay under 10^6
"""
T = time()

s = 1
for i in prime_sieve(100):
    s *= i
    if s > 10**6:
        print(s // i)
        break

print('time elapsed:', time() - T)
Exemplo n.º 25
0
from math import floor
from euler import prime_sieve
from time import time
T = time()

square_max = floor(50**(1/2)*10**(6/2))
cube_max = floor(50**(1/3)*10**(6/3))
fourth_max = floor(50**(1/4)*10**(6/4))
limit = 50*10**6

numbers = []
# can be optimized by just having one list of primes,
# this is sufficient for the task at hand, however
for i in prime_sieve(square_max):
    for j in prime_sieve(cube_max):
        for k in prime_sieve(fourth_max):
            num = (i**2 + j**3 + k**4)
            if num < limit:
                numbers.append(num)

print(len(set(numbers)))
print("time elapsed:", time() - T)
Exemplo n.º 26
0
from euler import prime_sieve, isprime
import time


def is_square(n):
    x = int((n / 2)**0.5)
    if 2 * x * x == n:
        return True
    else:
        return False


start = time.time()
num = 3
result = 0
while True:
    flag = False
    if not isprime(num):
        for item in prime_sieve(num):
            if is_square(num - item):
                flag = True
                break
        if not flag:
            result = num
            break
    num += 2
spend = time.time() - start
print "The result is %s and take time is %f" % (result, spend)
Exemplo n.º 27
0
# coding=utf-8

'''
Problem 35
17 January 2003

The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.

There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.

How many circular primes are there below one million?
'''

import euler
primes = dict.fromkeys(euler.prime_sieve(10**6), True)
def is_circular_prime(n):
  x = str(n)
  for i in range(0, len(x)):
    if int(x[i:] + x[:i]) not in primes:
      return False
  return True
print sum(1 for n in primes if is_circular_prime(n))
Exemplo n.º 28
0
# coding=utf-8
'''
Problem 35
17 January 2003

The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.

There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.

How many circular primes are there below one million?
'''

import euler
primes = dict.fromkeys(euler.prime_sieve(10**6), True)


def is_circular_prime(n):
    x = str(n)
    for i in range(0, len(x)):
        if int(x[i:] + x[:i]) not in primes:
            return False
    return True


print sum(1 for n in primes if is_circular_prime(n))
Exemplo n.º 29
0
from euler import prime_sieve


def quad_form(n, a, b):
    return n**2 + a * n + b


max_n = 1000
max_a = 1000
max_b = 1001
primes = list(prime_sieve(quad_form(max_n, max_a, max_b)))
b_vals = list(prime_sieve(max_b))

best = [0, 0, 0]
for b in b_vals:
    print(b)
    a_vals = filter(lambda a: a < b, map(lambda p: p - b - 1, primes))
    for a in a_vals:
        n = 0
        while quad_form(n, a, b) in primes:
            n += 1
        if n > best[2]:
            best = [a, b, n]
print(best)
print(best[0] * best[1])
Exemplo n.º 30
0
Arquivo: 27.py Projeto: higgsd/euler
# -59231
import euler
N = 1000
M = 80
m = -1
ab = 0
sieve = euler.prime_sieve(M * M + M * N + N)
for a in xrange(1-N, N):
    for b in xrange(2, N):
        n = 0
        while True:
            c = n * n + a * n + b
            if c < 2 or not sieve[c]:
                if n > m:
                    m = n
                    ab = a * b
                break
            n += 1
print ab
Exemplo n.º 31
0
import time
from euler import prime_sieve

start = time.time()

result = 1
for i in prime_sieve(20):
    result *= i

result = result*2*2*2*3
# from 1-20 they are prime:2,3,5,7,11,13,17,19
# analysis the other we need 2**4 and 3**2
time_take = time.time() - start
print "The sum is %s and take time is %f" %(result , time_take)
Exemplo n.º 32
0
# coding=utf-8
'''
Problem 50
15 August 2003

The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13

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?
'''

import euler

primes = euler.prime_sieve(10**4)
longest = primesum = 1
for i in range(len(primes)):
    for j in range(i + longest, len(primes)):
        if (sum(primes[i:j]) < 10**6) and euler.is_prime(sum(primes[i:j])):
            longest = j - i
            primesum = sum(primes[i:j])
print primesum
Exemplo n.º 33
0
from euler import isprime
from euler import prime_sieve
import time


def circular(n):
    num = str(n)
    for i in range(len(str(n))):
        cirnum = int(num[i:] + num[:i])
        if not isprime(cirnum):
            return False
    return True


start = time.time()
result = sum([1 for i in prime_sieve(10**6) if circular(i)])
time_spend = time.time() - start
print "The result is %d and time used is:%f s" % (result, time_spend)
Exemplo n.º 34
0
# April 25, 2016

# Fermat's Little Theorem
# 1/d has a cycle of n digits if 10^n - 1 mod d = 0 for prime d

from euler import prime_sieve

for d in list(prime_sieve(1000))[::-1]:
    period = 1
    while pow(10, period, d) != 1:
        period += 1
    if d - 1 == period:
        break

print d
Exemplo n.º 35
0
# coding=utf-8

"""
Problem 37
14 February 2003

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.
"""

import euler


def truncatable_prime(n):
    if n < 10:
        return False
    for i in range(1, len(str(n))):
        if not euler.is_prime(int(str(n)[i:])) or not euler.is_prime(int(str(n)[:-i])):
            return False
    return True


print sum(i for i in euler.prime_sieve(10 ** 6) if truncatable_prime(i))
Exemplo n.º 36
0
def sum_of_primes(m):
    return sum(prime_sieve(m))
Exemplo n.º 37
0
def count_circular_primes(r, c=0):
    for x in prime_sieve(r):
        if circular_prime(x):
            c += 1
    return c
Exemplo n.º 38
0
from euler import prime_sieve
import time

start = time.time()

result = sum(prime_sieve(2 * 10**6))
time_take = time.time() - start
print "The sum is %s and take time is %f" % (result, time_take)
Exemplo n.º 39
0
from euler import isprime
from euler import prime_sieve
import time


def trunc(n):
    num = str(n)
    for i in range(len(str(n))):
        cirnum = int(num[i:])
        if not isprime(cirnum):
            return False
    for i in range(len(str(n))):
        cirnum = int(num[:len(num) - i])
        if not isprime(cirnum):
            return False
    return True


start = time.time()
result = sum([i for i in prime_sieve(10**6) if trunc(i)]) - 2 - 3 - 5 - 7
time_spend = time.time() - start
print "The result is %d and time used is:%f s" % (result, time_spend)
Exemplo n.º 40
0
T = time()


def is_permutation(n1, n2):
    if sorted(str(n1)) == sorted(str(n2)):
        return True
    else:
        return False

n_max = 10**7
search_range = 1000
search_start = floor(sqrt(n_max)) - search_range
search_end = floor(sqrt(n_max)) + search_range

prime_list = []
for prime in prime_sieve(search_end):
    if prime > search_start:
        prime_list.append(prime)

candidate = 1
smallest_ratio = 10
for i in range(len(prime_list)):
    for j in range(i, len(prime_list)):
        n = prime_list[i]*prime_list[j]
        if n >= 10**7:
            break
        phi_n = phi(n)
        ratio = n/phi_n
        if is_permutation(n, phi(n)) and ratio < smallest_ratio:
            candidate = n
            smallest_ratio = ratio
Exemplo n.º 41
0
from euler import prime_sieve, truncations


primes=set(prime_sieve(1000000))


def compute():
    def is_truncated_prime(n):
        if n in [2, 3, 5, 7]:
            return False
        return all([p in primes for p in truncations(n)])
    return sum([p for p in primes if is_truncated_prime(p)])


if __name__ == "__main__":
    print(compute())