Ejemplo n.º 1
0
Archivo: 357.py Proyecto: julenka/euler
""" Prime generating integers

Consider the divisors of 30: 1,2,3,5,6,10,15,30.
It can be seen that for every divisor d of 30, d+30/d is prime.

Find the sum of all positive integers n not exceeding 100 000 000
such that for every divisor d of n, d+n/d is prime.

"""
__author__ = 'julenka'

from primes import primesfrom2to
import math

max_value = 100000000
primes = set(primesfrom2to(max_value * 2))

valid = []
result = 0

def test_number(n):
    for i in xrange(1, int(math.sqrt(n)) ):
        if n % i == 0:
            if n / i + i in primes:
                return True
    return False

for i in xrange(1, max_value):
    if test_number(i):
        result += i
Ejemplo n.º 2
0
        divisors.append(str(divisor))
    return divisors


if __name__ == "__main__":
    import math
    T = int(sys.stdin.readline()) #number of test cases

    for i in xrange(1,T+1):
        N,J = sys.stdin.readline().split(' ')
        N = int(N)
        J = int(J)
        print 'Case #%d:'%i

        min_value = 2**(N-1) +1    #First and last digits are 1
        max_value = 2**N - 1       #All 1's

        #Generate primes
        MAX_PRIME = 100000
        primes = primesfrom2to(MAX_PRIME)

        j = 0
        for candidate in xrange(min_value,max_value,2):
            candidate_binary = bin(candidate)[2:]
            divisors = check_coinjam(candidate_binary,primes)
            if divisors:
                print candidate_binary, ' '.join(divisors)
                j+=1
            if j == J: #we are done
                break
Ejemplo n.º 3
0
from primes import primesfrom2to
import math
import time

primes = primesfrom2to(10**7)

# 1. Find all primitive pytagorean triples
# 2. Check if their line lengths are unique - if not remove them
# 3. scale them up and add to the sum


def generate_prime_products(p_id,
                            prev_product,
                            upper_product_limit,
                            lower_product_limit,
                            exception_primes=None):
    # yield []
    global primes

    if prev_product == 1:
        yield 1, []

    for current_p_id in range(p_id, len(primes) + 1):
        if prev_product * primes[current_p_id] > upper_product_limit:
            return

        if exception_primes and primes[current_p_id] in exception_primes:
            continue

        k = 1
        current_product = prev_product * (primes[current_p_id]**k)
Ejemplo n.º 4
0
Find the value of n ≤ 1,000,000 for which n/φ(n) is a maximum.

FORMULA:
φ(n) = n * PRODUCT[unique prime factors p of n] ( 1 - 1/p)
"""

from primes import primesfrom2to
from collections import defaultdict

MAX_VAL = 10**6

# n->set(divisors)
# divisors is set of unique prime factors only
divisor_map = {}

primes = [1] + list(primesfrom2to(MAX_VAL))

# print primes

print "getting unique prime divisors..."
for i in xrange(1, MAX_VAL + 1):
    if i % 10**3 == 0:
        print i
    divisor_map[i] = set()
    j = 1
    while j < len(primes) and primes[j] <= i:
        if i % primes[j] == 0:
            divisor_map[i].add(primes[j])
            other = i / primes[j]
            divisor_map[i] = divisor_map[i].union(divisor_map[other])
            break
Ejemplo n.º 5
0
from primes import primesfrom2to
import math

max_sum = 50*(10**6)
primes = primesfrom2to(int(math.sqrt(max_sum)))

print("Min prime = ", primes[0])
print("Max prime = ", primes[-1])

# some caching for speedup
primes_squared = []
lim = max_sum - (2**3 + 2**4)
for p in primes:
    pp = p*p
    if pp > lim:
        break
    primes_squared.append(pp)
primes_cubed = []
lim = max_sum - (2**2 + 2**4)
for p in primes:
    ppp = p**3
    if ppp > lim:
        break
    primes_cubed.append(ppp)
primes_fourth = []
lim = max_sum - (2**2 + 2**3)
for p in primes:
    pppp = p**4
    if pppp > lim:
        break
    primes_fourth.append(pppp)
Ejemplo n.º 6
0
from primes import primesfrom2to
import time
import itertools

start = time.time()

presumed_length = 4  # presumed max length of the primes

primes = primesfrom2to(10**(2 * presumed_length))
primes = set([str(p) for p in primes if p > 10**presumed_length])

possible_primes = set([str(p) for p in primesfrom2to(10**presumed_length)])
print("Calculated primes in ", time.time() - start)

# 5 primes
# for every of these 5 primes:
# - there exist at least 5 other primes which end with them
# - there exist at least 5 other primes which start with them

total_possible_pairs = []

# for p in possible_primes:
#     possible_pairs = []

#     # p must have 8 possible pairs to be a possible prime
#     for pr in primes:
#         if len(pr) > len(p):
#             if pr.endswith(p) or pr.startswith(p):
#                 c = pr.replace(p, "")
#                 if c in primes:
#                     possible_pairs.append((p,c))
Ejemplo n.º 7
0
Archivo: 058.py Proyecto: julenka/euler
	42 21 22 23 24 25 26
	43 44 45 46 47 48 49

	It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting 
	is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ~= 62%.

	If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. 
	If this process is continued, what is the side length of the square spiral for which the ratio of primes along 
	both diagonals first falls below 10%?
"""
__author__ = "Julia Schwarz"

from primes import primesfrom2to


primes = set(primesfrom2to(10**9))

pct = 1.0
level = 1
diagonals = [1]
num_primes = 0
print "level, side_length, n_diagonals, n_primes, pct"
while pct >= 0.1:
	side_length = 2 * level + 1
	square = side_length ** 2
	for i in xrange(4):
		corner = square - (side_length - 1) * i
		diagonals.append(corner)
		if corner in primes:
			num_primes += 1
	pct = float(num_primes) / len(diagonals)
Ejemplo n.º 8
0
""" Prime power triples
The smallest number expressible as the sum of a prime square, prime cube, and prime fourth power is 28.
In fact, there are exactly four numbers below fifty that can be expressed in such a way:

28 = 22 + 23 + 24
33 = 32 + 23 + 24
49 = 52 + 23 + 24
47 = 22 + 33 + 24

How many numbers below fifty million can be expressed as the sum of a prime square,
prime cube, and prime fourth power?
"""
__author__ = 'julenka'

from primes import primesfrom2to
# 4th root of 50,000,000 is 84

primes = primesfrom2to(8000)
print primes
count = 0

max_value = 50000000
numbers = set()
for first in primes:
    for second in primes:
        for third in primes:
            sum_primes = first**2 + second**3 + third**4
            if sum_primes < max_value:
                numbers.add(sum_primes)

print len(numbers)
Ejemplo n.º 9
0
#!/usr/bin/python
import primes as prms

ofile=open("multiplesTo1MilTest.txt","w")
ofile.write("0\n1\n")
bigN=1000000

primes=prms.primesfrom2to(bigN)

decomposed=[list() for i in range(bigN+1)]
for i in range(2,bigN+1):
    cm=list()
    val=int(i)
    if i in primes:
        cm=[i]
    else:
        for p in primes:
            if i%p==0:
                cm.append(p)
                cm+=decomposed[i/p]
                break

    decomposed[val]=list(cm)

    ofile.write(" ".join(map(str,cm))+"\n")
Ejemplo n.º 10
0
Archivo: 069.py Proyecto: julenka/euler
Find the value of n ≤ 1,000,000 for which n/φ(n) is a maximum.

FORMULA:
φ(n) = n * PRODUCT[unique prime factors p of n] ( 1 - 1/p)
"""

from primes import primesfrom2to
from collections import defaultdict

MAX_VAL = 10 ** 6

# n->set(divisors)
# divisors is set of unique prime factors only
divisor_map = {}

primes = [1] + list(primesfrom2to(MAX_VAL))

# print primes

print "getting unique prime divisors..."
for i in xrange(1, MAX_VAL + 1):
    if i % 10 ** 3 == 0:
        print i
    divisor_map[i] = set()
    j = 1
    while j < len(primes) and primes[j] <= i:
        if i % primes[j] == 0:
            divisor_map[i].add(primes[j])
            other = i / primes[j]
            divisor_map[i] = divisor_map[i].union(divisor_map[other])
            break
Ejemplo n.º 11
0
result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes,
792, represents the lowest sum for a set of four primes with this property.

Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.
"""

import itertools
from primes import primesfrom2to
from collections import defaultdict
from math import factorial
import sys

MAX_PRIME = 10 ** 9
N = 4
print "finding primes..."
primes = set(primesfrom2to(MAX_PRIME))
candidates = primesfrom2to(10 ** 5)
def test(a):
    for p1, p2 in itertools.permutations(a, 2):
        s1, s2 = str(p1), str(p2)
        if int(s1 + s2) not in primes:
            return False
    return True

def choose(n, r):
    """
    n choose r
    """
    return factorial(n) / (factorial(n - r) * factorial(r))

def printline(s):
Ejemplo n.º 12
0
Archivo: 087.py Proyecto: julenka/euler
The smallest number expressible as the sum of a prime square, prime cube, and prime fourth power is 28.
In fact, there are exactly four numbers below fifty that can be expressed in such a way:

28 = 22 + 23 + 24
33 = 32 + 23 + 24
49 = 52 + 23 + 24
47 = 22 + 33 + 24

How many numbers below fifty million can be expressed as the sum of a prime square,
prime cube, and prime fourth power?
"""
__author__ = 'julenka'

from primes import primesfrom2to
# 4th root of 50,000,000 is 84


primes = primesfrom2to(8000)
print primes
count = 0

max_value = 50000000
numbers = set()
for first in primes:
    for second in primes:
        for third in primes:
            sum_primes = first ** 2 + second ** 3 + third ** 4
            if sum_primes < max_value:
                numbers.add(sum_primes)

print len(numbers)
Ejemplo n.º 13
0
import time
import numpy as np


def numbers_on_diagonals(side_length):
    nums = [1]
    for s in range(3, side_length, 2):
        for i in range(4):
            nums.append(nums[-1] + s - 1)
    return nums


# print(numbers_on_diagonals(7))

s = time.time()
primes = primesfrom2to(1000000000)
p_ind = 0
# primes = np.array(primes)
print("Calculated ", len(primes), " primes in ", time.time() - s, " seconds!")


def is_prime(num, next_num=None):
    global primes
    global p_ind
    i = p_ind
    while i < len(primes):
        if primes[i] >= num:
            break
        else:
            i += 1
    # for i, p in enumerate(primes):
Ejemplo n.º 14
-1
5 + 3 + 2
3 + 3 + 2 + 2
2 + 2 + 2 + 2 + 2

What is the first value which can be written as the sum of primes in over five thousand different ways?

"""
__author__ = 'julenka'

from primes import primesfrom2to
import sys
import itertools
if len(sys.argv) < 2:
    print "usage: {} prime_max_value max_primes_in_sum".format(__file__)
    exit(1)
prime_max_value = int(sys.argv[1])
max_primes_in_sum = int(sys.argv[2])
primes = primesfrom2to(prime_max_value)

upper_bound = 83

from collections import Counter
prime_summations_count = Counter()
for combination_length in xrange(1, max_primes_in_sum + 1):
    candidate_primes = [x for x in primes if 2 * combination_length - 2 + x < upper_bound]
    for combinations in itertools.combinations_with_replacement(candidate_primes, combination_length):
        prime_sum = sum(combinations)
        prime_summations_count[prime_sum] += 1

prime_summations_gt_5000 = filter(lambda (x, y): y > 5000, prime_summations_count.items())
print sorted(prime_summations_gt_5000)