Ejemplo n.º 1
0
def prime_obsession():
    primes = set(prime_sieve(510))
    prime_count = 0
    for num in solved_set:
        if num in primes:
            prime_count += 1
    print "Prime Obsession, solve:", 50 - prime_count
Ejemplo n.º 2
0
def main(N):
    primes = prime_sieve(N)

    factorizations = [(2, 2, 2), (4, 2), (8, 1)]

    length = len(primes)

    vals = set([])

    for a in range(length):
        for b in range(a + 1, length):
            val = a**3 * b
            if val > N:
                break
            if not (val in vals):
                vals.add(val)

    for a in primes:
        val = a**7
        if val > N:
            break
        if not (val in vals):
            vals.add(val)

    for a in range(length):
        for b in range(a + 1, length):
            for c in range(b + 1, length):
                val = primes[a] * primes[b] * primes[c]
                #print val
                if val > N:
                    break
                if not (val in vals):
                    vals.add(val)

    print len(vals)
Ejemplo n.º 3
0
def main ():
  max_prime = 10**8-1
  p = prime_sieve(max_prime)
  primes = set(p)
  test_p = filter(lambda i: len(str(i)) <= int(ceil(len(str(max_prime))/2.)), p)

  def cat_set_is_prime(prime_set):
    test_num = prime_set[-1]
    for num in prime_set[:-1]:
      if int(''.join(map(str, [num, test_num]))) not in primes or int(''.join(map(str, [test_num, num]))) not in primes:
        return False
    return True

  # get 2-tuples that match the criterion
  new_tup_list = sorted(set([combo for combo in combinations(test_p, 2) if cat_set_is_prime(combo)]))

  # try to add each test_p to the combos to make n+1 tuples satisfying the criterion
  for tup_size in range(3, 5+1):
    cur_tup_list = new_tup_list
    new_tup_list = []
    for tup in cur_tup_list:
      for new_num in test_p:
        if tup[-1] < new_num:
          cand = tuple(list(tup) + [new_num])
          if cat_set_is_prime(cand):
            new_tup_list.append(cand)

  print '\nAnswer: {0}'.format(sum(new_tup_list[0]))
  pass
Ejemplo n.º 4
0
def is_squarefree(n, k):
	primes = prime_sieve(n)
	for p in primes:
		num = num_primes(p, n) - num_primes(p, k) - num_primes(p, n-k)
		if num >= 2:
			return False
	return True
Ejemplo n.º 5
0
def main(N=5):
    primes = prime_sieve(10000)
    result = False
    while not result:
        my_list = [primes.pop(0)]
        result = iter_loop(my_list, primes, N)

    return sum(result)
Ejemplo n.º 6
0
def main():
    primes = prime_sieve(500)

    curr = 1
    for i in primes:
        if curr * i > bound:
            return curr
        else:
            curr *= i
def ans(n):
    if n < 7: return 3
    primes = prime_sieve(n)
    for p in primes[::-1]:
        i = 1
        # while 10**i % p != 1: i += 1
        while pow(10, i, p) != 1:
            i += 1  #this solves HackerRank constraints, spent a long time on this
        if p - 1 == i:
            return p  #this is the Number Theory trick: Fermat Little theory
def HackerRankSol():
    primes = prime_sieve(1000100)
    sum_primes = [0]
    for i in range(1, len(primes) + 1):
        sum_primes.append(sum_primes[i - 1] + primes[i - 1])

    t = int(raw_input().strip())
    for a0 in xrange(t):
        n = int(raw_input().strip())
        print sum_primes[bisect_right(primes, n)]
Ejemplo n.º 9
0
def main ():
  max_n = 50*10**6

  # get the max primes for each exponent slot
  max_square = int((max_n - 2**3 - 2**4)**(1/2.))+1
  max_cube   = int((max_n - 2**2 - 2**4)**(1/3.))+1
  max_quart  = int((max_n - 2**2 - 2**3)**(1/4.))+1
  
  # sieve for the possible sets
  p_2 = prime_sieve(max_square)
  p_3 = prime_sieve(max_cube)
  p_4 = prime_sieve(max_quart)
  
  # build all feasible combos & filter
  pos_tups = [(i ,j, k) for i in p_2 for j in p_3 for k in p_4]
  pos_nums = [t[0]**2 + t[1]**3 + t[2]**4 for t in pos_tups]

  sub_max_nums = filter(lambda i: i < max_n, pos_nums)

  print '\nAnswer: {0}'.format(len(set(sub_max_nums)))
  pass
def pollard_p_minus_1(n, max_iter, b):
    """Performing Pollard p- 1 factorization,
    with odd number input"""
    for _ in range(max_iter):
        primes = prime_sieve(b)
        for i in range(len(primes)):
            primes[i] = primes[i] ** (int(log(n, primes[i])))
        m = reduce(op.mul, primes)
        g = gcd(modularexponenation(2, m, n) - 1, n)
        if 1 < g < n:
            return g
        if g == 1:
            b += (b // 5)
        if g == n:
            b -= (b // 5)
Ejemplo n.º 11
0
def main ():

  cases = filter(lambda i: i < 10**7, map(lambda t: t[0]*t[1], combinations(prime_sieve(int(1.5*(10**7)**.5)),2)))
  print ''
  tot_tups = []
  for n in cases:
    f = uniq_f(n)
    tot_ratio =  reduce(mul, map(lambda p:1-p**-1, f))**-1
    tot = int(round(n / tot_ratio))
    
    if is_perm(n, tot):
      tot_tups.append((tot_ratio, n, tot))
  
  for tup in sorted(tot_tups)[:10]:
    print tup
  
  pass
Ejemplo n.º 12
0
def main(N, limit):
	def fn(reps):
		return product(primes, repeat = reps)

	primes = prime_sieve(N+1)
	rep_limit = int(ceil(log(limit, 2)))
	#print list(product(primes, repeat=reps))
	#print map(lambda reps: list(product(primes, repeat = reps)), range(1, rep_limit))
	filtered = set([])
	my_list = chain.from_iterable(map(fn, range(1, rep_limit)))
	#prods = [x for x in my_list if x < limit]
	ctr = 0
	for item in my_list:
		prod_val = prod(item, limit)
		if prod_val > 0 and prod_val not in filtered:
			filtered.add(prod_val)
			ctr += 1

	#prods = [x for x in chain.from_iterable(map(lambda reps: product(primes, repeat = reps), range(1, rep_limit))) if prod(x, limit) > 0]
	#print prods
	print ctr+1
def segmented_sieve(n):
    delta = n // int(sqrt(n))

    def calculate_smallest_mult(a, p):
        left = a - delta + 1
        left_mul = (left) // p
        tmp = p * left_mul
        if tmp < left:
            return tmp + p
        else:
            return tmp

    ms = []  # initialize array of top of segments
    primes = []  # initialize primes array
    i = 2 * delta  # used to create first delta primes
    ind = delta

    while i <= n:
        ms.append(i)
        i += delta
    primes = prime_sieve(delta)

    k = 1  # index of numbers in ms
    for num in ms:  # num is another starting from the 2*delta topmost value of segments
        arr = [True] * delta
        ind = 0
        p = primes[ind]
        while p <= int(sqrt(num)):
            start = calculate_smallest_mult(num, p)
            while start <= num:
                # print(arr)
                arr[start - delta * k - 1] = False
                start += p
            ind += 1
            p = primes[ind]
        for x in range(len(arr)):
            if arr[x] is True:
                primes.append(x + delta * k + 1)
        k += 1
    return primes
Ejemplo n.º 14
0
def sol_2():
    primes = prime_sieve(100000)

    def is_prime_2(n):
        if primes[bisect_left(primes, n)] == n: return True
        return False

    def formula(i, j, k):
        return k**2 + i * k + j

    n = int(raw_input().strip())

    max_primes, resI, resJ = 0, 0, 0
    for i in xrange(-n, n):
        for j in xrange(i, n):
            k = 0
            while is_prime_2(formula(i, j, k)):
                k += 1
            if k - 1 > max_primes:
                max_primes = k - 1
                resI, resJ = i, j

    print resI, resJ  #this solves all the HackerRank test cases
Ejemplo n.º 15
0
def F2(n):
    target = 20010
    primes = prime_sieve(10**7)

    base = 308
    factor = 1

    count = 0
    for p in [1] + primes:
        num = base * p

        while True:
            factor = 2
            if test_valid1(num, primes, target):
                count += 1
                if count == n:
                    return num
                num = base * p * factor
                factor += 1
            else:
                break
        factor += 1

    return num
Ejemplo n.º 16
0
def F3(n):
    target = 20010

    base = 308
    factor = 1
    primes = prime_sieve(10**7)

    count = 0
    for p in [1] + primes:
        factor = 1
        num = base * p * factor

        while True:
            if test_valid1(num, primes, target):
                print num, factorize(num)
                count += 1
                if count == n:
                    return num
                factor += 1
                num = base * p * factor
            else:
                break

    return num
Ejemplo n.º 17
0
from Euler import prime_sieve
primes = prime_sieve(500)
print primes
def num(x,y,z):
    return x**2+y**3+z**4

print num(2,2,2)
print num(3,2,2)
print num(5,2,2)
print num(2,3,2)
print num(3,3,2)
print num(5,3,2)
print num(7,2,2)
print num(2,2,3)
print num(3,2,3)
print num(2,3,3)

sum=[]

for x in prime_sieve(7072):
    for y in prime_sieve(369):
        for z in prime_sieve(90):
            if(num(x,y,z)<50000001):
                sum.append(num(x,y,z))

sum.sort()
print len(sum)
print len(set(sum))
'''
[See 129]

You are given that for all primes, p > 5, that p − 1 is divisible by A(p).
For example, when p = 41, A(41) = 5, and 40 is divisible by 5.

However, there are rare composite values for which this is also true; the first
five examples being 91, 259, 451, 481, and 703.

Find the sum of the first twenty-five composite values of n for which
GCD(n, 10) = 1 and n − 1 is divisible by A(n).
'''

from Euler import prime_sieve
from problem00129_repunitdivisibility import *

primes = set(prime_sieve(10**6))

valid = []
for n in (n for n in itertools.count(2) if n not in primes):
    k = A(n)
    if k > 0 and (n-1)%k==0:
        valid.append(n)
    if len(valid) == 25:
        break

ans = sum(valid)
print(ans)

Ejemplo n.º 19
0
import string
from Euler import prime_sieve, is_prime

 
def eight_prime_family(prime, rd):
  c=0
  for digit in '0123456789':
    n = int(string.replace(prime, rd, digit))
    if (n>100000 and is_prime(n)):
      c=c+1
  return c==8
  
primes = prime_sieve(999999)

for i in xrange(len(primes)):
	for digit in '0123456789':
		if(str(primes[i]).count(str(digit))==3):
			if (eight_prime_family(str(primes[i]), digit)):
				print primes[i]
				exit()
Ejemplo n.º 20
0
        return a % m
    else:
        raise ValueError("Reciprocal does not exist")


var = 0


def s(p):
    # (p-5)! + (p-4)! + (p-3)! + (p-2)! + (p-1)!
    # = (p-5)! * (1 + (p-4) + (p-4)(p-3) + (p-4)(p-3)(p-2) + (p-4)(p-3)(p-2)(p-1))
    # = (p-5)! * (1 + (-4) + (-4)(-3) + (-4)(-3)(-2) + (-4)(-3)(-2)(-1))
    # = (p-5)! * (1 + -4 + 12 + -24 + 24)
    # = (p-5)! * 9
    # = (p-1)! / ((p-1)(p-2)(p-3)(p-4)) * 9
    # = (p-1)! / ((-1)(-2)(-3)(-4)) * 9
    # = (p-1)! / 24 * 9
    # = (p-1)! * (3 * 3) / (3 * 8)
    # = (p-1)! * 3 / 8
    # = -1 * 3 / 8  (by Wilson's theorem)
    # = -3/8 mod p.
    # Every part of the equation is modulo a prime p > 4
    return (p - 3) * reciprocal_mod(8 % p, p) % p


psieve = prime_sieve(10**8)
for x in psieve:
    if x >= 5:
        var += s(x)
print var
Ejemplo n.º 21
0
#50. Find the prime below 1 million which is the sum of the most consecutive
#primes.

from Euler import prime_sieve
from Euler import is_prime
import time

primes = prime_sieve(100000)  #this takes some time if incremented
t_0 = time.clock()

chart = {
    (0, 1): 5
}  #(i,j) gives the sum of the primes from p[i] to p[j] inclusive


def sum_of_primes(i, j):  #uses chart to sum from p[i] to p[j] inclusive
    if (i, j) in chart:
        return chart[(i, j)]
    else:
        if i == 0:
            result = sum_of_primes(i, j - 1) + primes[j]
            chart[(i, j)] = result
            return result
        else:
            result = sum_of_primes(i - 1, j) - primes[i - 1]
            chart[(i, j)] = result
            return result


(highest, num_of_terms) = (41, 6)
starting_prime_index = 0
#!/usr/bin/env python

from Euler import prime_sieve
from bisect import bisect_right

primes = prime_sieve(2000000)
print reduce(lambda x, y: x + y, primes, 0)


#my awesome solution for the HackerRank version of the problem using caching and binary search in additio to the sieve
def HackerRankSol():
    primes = prime_sieve(1000100)
    sum_primes = [0]
    for i in range(1, len(primes) + 1):
        sum_primes.append(sum_primes[i - 1] + primes[i - 1])

    t = int(raw_input().strip())
    for a0 in xrange(t):
        n = int(raw_input().strip())
        print sum_primes[bisect_right(primes, n)]
Ejemplo n.º 23
0
from Euler import prime_sieve, is_prime

max = 1000000
primes = prime_sieve(max)
prime_sum = [0]

sum = 0
count = 0
while (sum < terms and is_prime(n)):
    (terms, max_prime) = (j - i, n)

print "Project Euler 50 Solution = ", max_prime, " with ", terms, " terms"
Ejemplo n.º 24
0
from math import sqrt
from Euler import prime_sieve


# for i in range(50):
#     print(i, unique_divisors(i))

N = 100000000

primes = set(prime_sieve(N))

def meets_criteria(n):
    if 1 + n not in primes:
        return False
    if 2 + n // 2 not in primes:
        return False
    divisors = [i for i in range(1, int(sqrt(n)) + 1) if n % i == 0]
    for d in divisors:
        print(d, n, d + n // d)
        if d + n // d not in primes:
            return False
    return True

def main(n):
    sum = 1  # as 1 works for the problem, but is the only odd to work, we set step size to 2
    for i in range(2, N+1, 2):
        if (meets_criteria(i)):
            sum += i
            print(i, "meets criteria")

    print(sum)
Ejemplo n.º 25
0
def M(p, q, N):
	primes  = prime_sieve(N)
	for p in primes:
		gen = (x for x in primes if x != p)
		for q in gen:
			while num1
Ejemplo n.º 26
0
    return int(temp)


def get_family_size(repeated_num, pattern_fam):
    family_size = 0

    for i in range(repeated_num, 10):
        if is_prime(generate_number(i, pattern_fam)):
            family_size += 1

    return int(family_size)


assumed_bound = 1000000
primes = prime_sieve(assumed_bound)
patterns5 = [[1, 0, 0, 0, 1], [0, 1, 0, 0, 1], [0, 0, 1, 0, 1],
             [0, 0, 0, 1, 1]]
patterns6 = [[1, 1, 0, 0, 0, 1], [1, 0, 1, 0, 0, 1], [1, 0, 0, 1, 0, 1],
             [1, 0, 0, 0, 1, 1], [0, 1, 1, 0, 0, 1], [0, 1, 0, 1, 0, 1],
             [0, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0, 1], [0, 0, 1, 0, 1, 1],
             [0, 0, 0, 1, 1, 1]]


# start main algorithm
def main():
    best = int(1000000)
    for i in range(11, 1000, 2):

        if i % 5 == 0:
            i += 2
Ejemplo n.º 27
0
from Euler import prime_sieve, is_perm, sqrt
 
min_q, i, L = 2, 0, 10**7
primes = prime_sieve(1.30*sqrt(L))
ll = 0.7*sqrt(L)
for n in range(len(primes)):
  if primes[n]>ll: break
del primes[:n]
 
for p1 in primes:
  i+=1
  for p2 in primes[i:]:
    n = p1 * p2
    if n > L: break
    phi = (p1-1) * (p2-1)
    q = n / float(phi)
    if is_perm(phi, n) and min_q>q: min_q, min_n = q, n
 
print "Answer to PE70 = ",min_n
Ejemplo n.º 28
0
from Euler import prime_sieve, is_prime

result = int(100000000)
primes = prime_sieve(30000)
pairs = None


def concat(first, second):
    return int(str(first) + str(second))


def make_pairs(list_of_primes):
    pairs = list()
    if list_of_primes is None:
        return
    for elem in list_of_primes:
        for other_elem in list_of_primes:
            if elem is other_elem:
                continue
            pairs.append(concat(elem, other_elem))

    return pairs


def main():
    answers = list()
    for index_a in range(0, len(primes)):
        if primes[index_a] * 5 >= result: break
        if pairs[index_a] is None: pairs[index_a] = make_pairs([index_a])

        for index_b in range(index_a, len(primes)):
Ejemplo n.º 29
0
from Euler import prime_sieve

#From proposition 2, https://sriasat.files.wordpress.com/2012/12/eureka.pdf
n = 20000000
r = 15000000
my_sum = 0

for p in prime_sieve(n):
    p_exp = p
    while p_exp <= n:
        my_sum += p * (n // p_exp - r // p_exp - (n - r) // p_exp)
        p_exp *= p
print my_sum
Ejemplo n.º 30
0
'''
What is the 10,001st prime number?
'''

from Euler import prime_sieve

def nth(iterable, n):
    for i, value in enumerate(iterable):
        if i==n: return value
    raise RuntimeError("Iterable length {} < {}".format(i, n))


if __name__ == '__main__':
    ans = nth(prime_sieve(200000), 10000)
    print(ans)
Ejemplo n.º 31
0
def prime_factors(n):
    lim = n**0.5+1
    below_lim = lambda x: x < lim
    primes = prime_sieve(lim)
    return (p for p in itertools.takewhile(below_lim, primes) if n%p==0)
Ejemplo n.º 32
0
In fact, with the exception of p1 = 3 and p2 = 5, for every pair of consecutive
primes, p2 > p1, there exist values of n for which the last digits are formed
by p1 and n is divisible by p2. Let S be the smallest of these values of n.

Find ∑ S for every pair of consecutive primes with 5 ≤ p1 ≤ 1000000.
'''

from Euler import prime_sieve
import math

def S(p1, p2):
    # m * p2 = k * 10 ** e + p1
    # p1 and p2 are coprime so CRT

    # d = 10 ** e
    d = 10 ** math.ceil(math.log10(p1))

    # k * d + p1 == 0 (mod p2)
    # k == (p2 - p1) * d_inv (mod p2)
    # but precisely because p2 is prime we can take shortcut
    # and avoid doing modular inverse the long way
    d_inv = pow(d, p2-2, p2)
    k = (p2 - p1) * d_inv % p2

    return k * d + p1

primes = list(prime_sieve(1000000+100))
ans = sum(S(p1, p2) for p1, p2 in zip(primes, primes[1:]) if 5 <= p1 <= 1000000)
print(ans)
"""
Find the sum of all the primes below one-hundred thousand
that will never be a factor of R(10**n).
"""

from Euler import prime_sieve

ans = sum(p for p in prime_sieve(100000) if pow(10, 10 ** 20, p) != 1) + 3
print(ans)
Ejemplo n.º 34
0
#!/usr/bin/env python
import time
from Euler import prime_sieve

t_0 = time.clock()

primes = set(prime_sieve(1000000))

def is_truncatable(p):
    r = p
    while r/10 <> 0:
        r /= 10
        if r not in primes:
            return False
    m = 10
    while p % m <> p:
        if p % m not in primes:
            return False
        m *= 10
    return True


truncatable_primes = []
for i in primes - set([2,3,5,7]):
    if is_truncatable(i):
        truncatable_primes.append(i)
        if len(truncatable_primes) == 11:
            break

print "Found %d truncatable primes" % len(truncatable_primes)
print truncatable_primes
Ejemplo n.º 35
0
from Euler import prime_sieve, is_prime

max = 1000000
primes = prime_sieve(max)
prime_sum = [0]

sum = 0
count = 0
while (sum<terms and is_prime(n)):
            (terms, max_prime) = (j-i, n)

print "Project Euler 50 Solution = ", max_prime, " with ", terms, " terms"
It can be seen that the first eight rows of Pascal's triangle contain twelve
distinct numbers: 1, 2, 3, 4, 5, 6, 7, 10, 15, 20, 21 and 35.

A positive integer n is called squarefree if no square of a prime divides n.
Of the twelve distinct numbers in the first eight rows of Pascal's triangle,
all except 4 and 20 are squarefree. The sum of the distinct squarefree numbers
in the first eight rows is 105.

Find the sum of the distinct squarefree numbers in the first 51 rows of Pascal's
triangle.
"""

from math import factorial
from Euler import prime_sieve


def C(n, k):
    return factorial(n) // factorial(k) // factorial(n - k)


def square_free(n):
    return all(n % f != 0 for f in squares)


N = 51
numbers = {C(n, k) for n in range(N) for k in range(n)}
squares = [p ** 2 for p in prime_sieve(max(numbers) ** 0.5)]
ans = sum(n for n in numbers if square_free(n))
print(ans)
Ejemplo n.º 37
0
'''
Find the sum of all the primes below two million.
'''

from Euler import prime_sieve

ans = sum(prime_sieve(2*10**6))
print(ans)
Ejemplo n.º 38
0
def main(index, upper_bound):
    primes = prime_sieve(upper_bound)
    return primes[index]
Ejemplo n.º 39
0
#50. Find the prime below 1 million which is the sum of the most consecutive
#primes.

from Euler import prime_sieve
from Euler import is_prime
import time


primes = prime_sieve(100000) #this takes some time if incremented
t_0 = time.clock()

chart = {(0,1): 5} #(i,j) gives the sum of the primes from p[i] to p[j] inclusive
def sum_of_primes(i,j): #uses chart to sum from p[i] to p[j] inclusive
    if (i,j) in chart:
        return chart[(i,j)]
    else:
        if i==0:
            result = sum_of_primes(i,j-1) + primes[j]
            chart[(i,j)] = result
            return result
        else:
            result = sum_of_primes(i-1,j) - primes[i-1]
            chart[(i,j)] = result
            return result


(highest, num_of_terms) = (41,6)
starting_prime_index = 0
for i in xrange(0,4): #index of the starting prime
    m = num_of_terms
    for j in xrange(i+m,550): #index of the ending prime
'''
[See 129]

For example, R(10) = 1111111111 = 11×41×271×9091, and the sum of these prime
factors is 9414.

Find the sum of the first forty prime factors of R(10**9).
'''

from Euler import prime_sieve

# any factor of 111...[k] is also a factor of 999...[k]
# and 999...[k] is 10**k-1. so if the remainder is 1, the number is a factor
# however, skip 3, since it trivially divides 9
found = [p for p in prime_sieve(2E5) if pow(10, 10**9, p)==1][1:41]
assert len(found) == 40
ans = sum(found)
print(ans)
Ejemplo n.º 41
0
    return True


def miller_rabin_pass(a, s, d, n):
    a_to_power = pow(a, d, n)
    if a_to_power == 1:
        return True
    for i in range(s - 1):
        if a_to_power == n - 1:
            return True
        a_to_power = (a_to_power * a_to_power) % n
    return a_to_power == n - 1


lim = 10**7
sieve, primes = prime_sieve(lim)
print 'done sieving'


# From http://stackoverflow.com/a/171784
def get_divisors(n):
    factors = factor(n)
    nfactors = len(factors)
    f = [0] * nfactors
    while True:
        yield reduce(lambda x, y: x * y,
                     [factors[x][0]**f[x] for x in range(nfactors)], 1)
        i = 0
        while True:
            f[i] += 1
            if f[i] <= factors[i][1]:
Ejemplo n.º 42
0
from Euler import prime_sieve, is_prime
import string

def eight_prime_family(prime, rd):

  c=0

  for digit in '0123456789':

    n = int(string.replace(prime, rd, digit))

    if (n>100000 and is_prime(n)):
      c=c+1

  return c==8

for prime in prime_sieve(1000000):

  if (prime>100000):

    s = str(prime)

    last_digit = s[5:6]

    if (s.count('0')==3 and eight_prime_family(s,'0') \
     or s.count('1')==3 and last_digit != '1' and eight_prime_family(s,'1') \
     or s.count('2')==3 and eight_prime_family(s,'2')):
       print "Answer to PE51: ",s
def project_euler_10():
    '''Prints the sum of all the primes below two million.
    See the prime_sieve method in Euler.py for more details.'''

   # print(sum(prime_sieve(10)))
    print(sum(prime_sieve(2*10**6)))
Ejemplo n.º 44
0
#!/usr/bin/python -tt
import sys
sys.path.append('/Users/admin/Desktop/python-work/Project_Euler/primes')

from Euler import prime_sieve, is_prime
 
nmax = 0;
primes = prime_sieve(1000)
for a in range(-999,999,2):
  for b in primes:
    n = 1
    while is_prime(n**2 + a*n + b): n += 1
    if n>nmax: nmax, p = n, a*b
 
print "Answer to PE27 = ",p

def main():
  print 'hello'

# Standard boilerplate to call the main() function.
if __name__ == '__main__':
  main()

Ejemplo n.º 45
0
from Euler import prime_sieve, sqrt
L = 10**7
primes = prime_sieve(int(1.30 * sqrt(L)))
del primes[:int(0.6 * len(primes))]


def Eluer70(limit):
    min_q, min_n, i = 2, 0, 0
    for p1 in primes:
        i += 1
        for p2 in primes[i:]:
            if (p1 + p2) % 9 != 1: continue
            n = p1 * p2
            if n > limit: return min_n
            phi = (p1 - 1) * (p2 - 1)
            q = n / float(phi)
            if sorted(str(phi)) == sorted(str(n)):
                if min_q > q:
                    min_q = q
                    min_n = n


print Euler70(L)
Ejemplo n.º 46
0
#243. Find the smallest denominator d having a resilience less than
#15499/94744.

from Euler import prime_sieve

primes = prime_sieve(1000)

totient = 1
for k in range(1, 1000):
    first_k_primes = [p for (i, p) in enumerate(primes) if i < k]
    prime_product = reduce(lambda x,y:x*y, ((1-1./p) \
                                            for p in first_k_primes))
    n = reduce(lambda x, y: x * y, (p for p in first_k_primes))

    resilience = float(n) / (n - 1) * prime_product
    if resilience < 15499. / 94744:
        #print k, first_k_primes #yields 10,[2,3,...,29]
        break

#From the above test I only need to consider primes up to 29, i.e. the first 10.

primes = primes[:9]
prime_product = reduce(lambda x,y:x*y, ((1-1./p) \
                                            for p in primes))
n = 8 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23
print float(n) / (n - 1) * prime_product < 15499. / 94744
print n, "is our winner"

n = 16 * 9 * 5 * 7 * 11 * 13 * 17 * 19
print float(n) / (n - 1) * prime_product < 15499. / 94744
Ejemplo n.º 47
0
from Euler import factor, prime_sieve
from operator import mul
from collections import defaultdict
import sys

def prod(*args):
    return reduce(mul, *args)

def is_valid(*args):
    return prod(*args) == sum(*args)

# Return all decompositions of n into factors
primes = prime_sieve(10**6)
prime_set = set(primes)

def is_prime(n):
    return n in prime_set

# Return all decompositions of n
memo = {}
def D(n):
    # Memoize
    if n in memo: return memo[n]

    vals = [(n, )]
    #vals = []

    # Base case
    if is_prime(n) or n == 1:
        memo[n] = vals
        return vals
Ejemplo n.º 48
0
from Euler import prime_sieve, is_prime
import itertools

primes = prime_sieve(70)
prime_set = set(primes)


def is_prime_set(vals):
    subsets = itertools.combinations(vals, 2)
    failed_set = set([])
    for a, b in subsets:
        a = str(a)
        b = str(b)
        str1 = a + b
        str2 = b + a
        if not is_prime(int(str1)) or not is_prime(int(str2)):
            return False
    return True


def main():
    d = {}
    subsets = itertools.combinations(primes, 3)
    for s in subsets:
        if is_prime_set(s):
            print s
            if s[0] in d:
                d[s[0]].append(s)
            else:
                d[s[0]] = [s]
Ejemplo n.º 49
0
from itertools import permutations
from Euler import prime_sieve


def perm(k):
    sett = set()
    for z in permutations(str(k)):
        n = ""
        for t in z:
            n += t
        sett.add(int(n))
    return sett


k = set(prime_sieve(10000))
for i in k:
    if i > 1000:
        if i + 3330 in k and i + 3330 in perm(i):
            if i + 3330 * 2 in k and i + 3330 * 2 in perm(i):
                print i, i + 3330, i + 3330 * 2