コード例 #1
0
def pollard_p_minus_one(n, b=5, m=13, a=2):
    if b < 1:
        raise Exception('B must be bigger than 1')
    if b >= m:
        raise Exception('B must be less than sqrt(n)')
    if m >= b**2:
        raise Exception('M must be less than B^2')
    if m >= math.sqrt(n):
        raise Exception('M must be less than sqrt(n)')
    if a < 1:
        raise Exception('a must be bigger than 1')

    mb_primes = utils.primes(2, b)
    primes_mul = reduce(operator.mul, mb_primes, 1)

    b = (a**primes_mul) % n
    q = utils.gcd(b - 1, n)

    if q > 1:
        return q, n // q

    m_primes = utils.primes(b, m)
    for m in m_primes:
        fm = (b**(m - 1)) % n
        gm = utils.gcd(fm, n)
        if gm > 1:
            return gm, n // gm

    return math.nan, math.nan
コード例 #2
0
ファイル: problem-03.py プロジェクト: meetashok/projecteuler
def main():
    number = 600851475143
    sqrt = int(math.sqrt(number))

    for prime in reversed(primes(sqrt)):
        if number % prime == 0:
            return prime
コード例 #3
0
 def getFraction(self):
     n = 1
     d = 1
     for (p, a) in zip(utils.primes(), self):
         if a > 0: n *= p**a
         elif a < 0: d *= p**(-a)
     return (n, d)
コード例 #4
0
ファイル: 27_quadratic_primes.py プロジェクト: c0lon/euler
def most_consecutive_primes(n):
    # given n^2 + ax + b, assume the highest result we can get is 2n^2 + n
    # generate all primes up to that
    _primes = utils.primes(2*pow(n, 2) + n)
    primes = {}
    for p in _primes:
        primes[p] = True

    a, b = 0, 0
    ps = 0

    for _a in range(n):
        for _b in range(n):

            # consider all combos of positive/negative
            for __a, __b in [(_a, _b), (-_a, _b), (-_a, -_b), (_a, -_b)]:
                # create the function
                def f(x):
                    return pow(x, 2) + __a*x + __b

                # look for primes
                x = 0
                _ps = -1
                while primes.get(f(x)):
                    _ps += 1
                    x += 1

                if _ps > ps:
                    a, b = __a, __b
                    ps = _ps

    return a*b
コード例 #5
0
def main():
    result = 0
    while True:
        result += 1
        x = ways(take_upto(result, primes()), result)
        if x > 5000:
            break
    return result
コード例 #6
0
def getEpimoricZip(r):
    "(6/5) -> [(3/2,1), (5/4,-1)]"
    result = []
    while r != Rational(1):
        p, i = zip(utils.primes(), r)[-1]
        e = Rational(p, p-1)
        result.insert(0, (e, i))
        r /= e ** i
    return result
コード例 #7
0
def testRandom3Digit():
    nsamples = 10
    for i in range(nsamples):
        threeDigitPrimes = primes(1000)[2:]
        random.shuffle(threeDigitPrimes)
        p1, p2 = threeDigitPrimes[0], threeDigitPrimes[1]
        n = p1 * p2
        print("primes: " + str(p1) + ", " + str(p2))
        print(quadSieve(n))
        assert (quadSieve(n) == {p1, p2})
コード例 #8
0
ファイル: 26_reciprocal_cycles.py プロジェクト: c0lon/euler
def longest_recurring_cycle(n):
    for denom in utils.primes(n)[::-1]:
        period_length = 1

        # 1 % denom is always 1, so when it's seen again we know the period is over
        while pow(10, period, denom) != 1:
            period_length += 1

        # reptend prime check
        if denom - 1 == period_length:
            return denom
コード例 #9
0
def main():
    trunc_count = 11
    trunc_primes = []

    for p in take_from(10, primes()):
        if truncatable_prime(p):
            trunc_count -= 1
            trunc_primes.append(p)
            if trunc_count == 0:
                break

    return sum(trunc_primes)
コード例 #10
0
def compute():
    PRIMES = primes(1000)
    target = 10  # we are given that 10 only has 5 prime partitions
    while True:
        prime_partitions = [0] * (target + 1)
        prime_partitions[0] = 1
        for p in PRIMES:
            for j in range(p, target + 1):
                prime_partitions[j] += prime_partitions[j - p]
        if prime_partitions[target] > 5000:
            break
        target += 1
    return target
コード例 #11
0
def compute():
    # We are given that this pattern holds at least until 33
    # We will cheat a bit here and assume that this pattern will not hold until 10,000
    # This can be found with some experimentation
    prime_list_full = primes(10000)
    num = 35
    while True:
        prime_list = [p for p in prime_list_full if p < num]
        if not (any(
                sqrt(num / 2 - p / 2) == int(sqrt(num / 2 - p / 2))
                for p in prime_list)) and not is_prime(num):
            return num
        num += 2
コード例 #12
0
ファイル: problem-46.py プロジェクト: meetashok/projecteuler
def main():
    prime_numbers = utils.primes(10000)
    odd_composites = [n for n in range(2, 10000) if (utils.isprime(n) == False) & (n % 2 != 0)]

    for odd_composite in odd_composites:
        number_found = False
        for prime in prime_numbers:
            difference = odd_composite - prime
            if difference > 0:
                if np.sqrt(difference / 2) == int(np.sqrt(difference/2)):
                    number_found = True
        if number_found == False:
            return odd_composite
コード例 #13
0
def compute():
    LIMIT = 50_000_000
    max_prime = int(sqrt(LIMIT))  # prime**2 must be less than LIMIT
    PRIMES = primes(max_prime)
    numbers = set()
    for x in PRIMES:
        for y in PRIMES:
            for z in PRIMES:
                value = x**2 + y**3 + z**4
                if value < LIMIT:
                    numbers.add(value)
                else:
                    break
    return len(numbers)
コード例 #14
0
ファイル: p073.py プロジェクト: ericdahl/project-euler
def factor_map(max):
    m = {}
    
    primes = utils.primes(max)
    sprimes = set(primes)
    for n in xrange(1, max):
        if n in sprimes:
            m[n] = set()
            continue

        factors = []
        for p in primes:
            if p < n and n % p == 0:
                factors.append(p)
        m[n] = set(factors)
    return m
コード例 #15
0
ファイル: 49.py プロジェクト: Cawb07/projecteulerstuff
def run():
	to_proc = []
	for prime in primes(1000,10000):
		to_proc.append(prime)
	to_proc.sort()
	permutations = []
	for i in to_proc[:]:
		if len(permutations) == 2:
			break
		for j in xrange(1, (10000-i)/2):
			second = str(i+j)
			if is_prime(i+j) and is_permutation(str(i), second):
				third = i+j+j
				if is_prime(third) and is_permutation(second, str(third)):
					permutations.append((i,i+j,i+j+j))
	print permutations
コード例 #16
0
def main():
    primes_less_1000 = list(takewhile(lambda x: x < 1000, primes()))
    highest = [0, 0, 0]

    for a in range(-999, 1001):
        for b in primes_less_1000:
            n = 0
            while is_prime((n**2) + (a*n) + b):
                n += 1

            if n > highest[0]:
                highest[0] = n
                highest[1] = a
                highest[2] = b

    print(highest)
    return highest[1] * highest[2]
コード例 #17
0
def main():
    total = 0
    primes_less_limit = take_upto(MILL, primes())

    for p in primes_less_limit:
        n = p
        circular = True
        for _ in str(n):
            if not is_prime(n):
                circular = False
                break

            n = rotate_digits(n)

        if circular:
            total += 1

    return total
コード例 #18
0
ファイル: p051.py プロジェクト: ericdahl/project-euler
def main():
    length = 6
    primes = [str(prime) for prime in utils.primes(10 ** length) if 10 ** (length - 1) < prime < 10 ** length]
    counter = Counter()

    for prime in primes:
        digit_counter = Counter(prime)

        for d, digit_count in digit_counter.iteritems():
            if digit_count == 1:
                continue
            indices = [i for i, x in enumerate(prime) if x == d]
            for length in xrange(2, digit_count + 1):
                for i in itertools.combinations(indices, length):
                    counter.update([tuple([digit if digit_index not in i else -1 for digit_index, digit in enumerate(prime)])])

    result = counter.most_common(1)[0][0]

    for prime in primes:
        if is_match(result, prime):
            print prime
            break
コード例 #19
0
def factor(num, b):
    """
    factor using Pollard's p-1 method
    num: odd number to factor
    b: smoothness cap
    """

    primeList = utils.primes(b)
    m = 1

    for prime in primeList:
        exp = math.floor(math.log(b, prime))
        m *= pow(prime, exp)

    a = 2
    g = utils.xgcd(pow(a, m, num) - 1, num)[0]
    if (1 < g and g < num):
        return g
    elif (g == 1):
        # Increase B
        return -1
    elif (g == num):
        # Decrease B
        return -2
コード例 #20
0
ファイル: problem60.py プロジェクト: snuderl/Project-euler
import utils
from itertools import combinations, takewhile, product, chain

primesSet = list(map(str, utils.primes(100000000)))
primes = list(takewhile(lambda x: int(x) < 10000, list(primesSet)))
primesSet = set(primesSet)


print len(primes), len(primesSet)


def checkAllPrimes(x):
    if not len(set(x)) == len(x):
        return False
    for y, z in combinations(x, 2):
        if not (y + z in primes and z + y in primes):
            return False
    return True


def checkAllPrimes2(x1, x2):
    for y in x1:
        if not (y + x2 in primes and x2 + y in primes):
            return False
    return True


# pairs = None

# print "Got primes"
# pairs = list(filter(checkAllPrimes,
コード例 #21
0
ファイル: 0003.py プロジェクト: CodedSakura/ProjectEuler
from utils import primes

v = 600851475143
lim = v**.5
last = 1
for i in primes():
    if v % i == 0:
        last = i
    if i > lim:
        break

print(last)
コード例 #22
0
ファイル: 77.py プロジェクト: crazymerlyn/code
from utils import primes

limit = 100

ps = primes(limit)
count = [[0 for _ in ps] for _ in range(limit+1)]

for n in range(1, limit+1):
    for i, p in enumerate(ps):
        if p == n: count[n][i] += 1
        count[n][i] += count[n-p][i]
        if i > 0:
            count[n][i] += count[n][i-1]

for n, cs in enumerate(count):
    if cs[-1] > 5000:
        print n
        break

コード例 #23
0
ファイル: 216.py プロジェクト: crazymerlyn/code
    r = pow(n, (q + 1) / 2, p)

    while t != 1:
        i = find_sq_num(t, p)
        if i >= m: return
        b = pow(c, 2 ** (m - i - 1), p)
        m = i
        c = b * b % p
        t = t * b * b % p
        r = r * b % p
    yield r
    yield p - r

limit = 5 * 10 ** 7

ps = list(primes(int(2 ** 0.5 * limit)))

els = array.array('B', '1' * (limit + 1))

for p in ps[1:]:
    for r in calculate_r(p):
        init = r if 2 * r * r - 1 != p else r + p
        for k in xrange(init, limit+1, p):
            els[k] = 0

count = 0
for i in xrange(2, limit + 1):
    if els[i]:
        count += 1
print count
コード例 #24
0
from utils import primes
from math import log


def powers(l, limit):
    res = l
    while res <= limit:
        yield res
        res *= l


limit = 10**7
ps = list(primes(limit / 2))

res = 0
for lp in ps[::-1]:
    for s in ps:
        if lp * s > limit: break
        if s >= lp: break
        ans = 0
        for l in powers(lp, limit):
            if l * s > limit: break
            ans = max(ans, l * list(powers(s, limit / l))[-1])
        res += ans
print res
コード例 #25
0
from utils import primes, modinv

limit = 1000000

ps = list(primes(limit + 100))[2:]

res = 0
for p1, p2 in zip(ps, ps[1:]):
    if p1 > limit: break
    power10 = 10 ** len(str(p1))
    res += ((p2 - p1) * modinv(power10, p2) % p2) * power10 + p1
print res

コード例 #26
0
ファイル: 204.py プロジェクト: crazymerlyn/code
from utils import primes

ty = 100
limit = 10**9

ps = list(primes(ty))
ns = [1]

res = set()
while ns:
    n = ns.pop()
    if n in res: continue
    res.add(n)
    for p in ps:
        x = n * p
        if x <= limit:
            ns.append(x)
print len(res)
コード例 #27
0
ファイル: problem50.py プロジェクト: snuderl/Project-euler
import utils
import itertools
import time

start = time.time()
BOUND = 1000000
current = (0,1)

primes = list(utils.primes(BOUND))
prime_arr = [False] * BOUND

for p in primes:
	prime_arr[p] = True

print ("Primes generated")
max_length = 0
for i in range(0, len(primes)):
	s = 0
	curr_length = 0
	for p in primes[i:]:
		s += p
		if s >= BOUND:
			break
		curr_length += 1
		if prime_arr[s]:
			if curr_length > max_length:
				max_length = curr_length
				print "New max: %s" % max_length
				print sum(primes[i:i+curr_length])

print (time.time() - start)
コード例 #28
0
ファイル: problem47.py プロジェクト: snuderl/Project-euler
import utils
from collections import Counter
from itertools import tee, izip

def window(iterable, size):
    iters = tee(iterable, size)

    for i in xrange(1, size):
	    for each in iters[i:]:
	        next(each, None)
    return izip(*iters)

MAX = 1000000
primes = utils.primes(MAX)
def factor_consequtive(x):
	factors = utils.factor(x, primes)
	counts = Counter(factors)
	for k in counts:
		yield k ** counts[k]

def generate_consequtive():
	i = 1
	while True:
		yield set(factor_consequtive(i))
		i += 1


for a, b, c, d in window(generate_consequtive(), 4):
	if len(a.union(b).union(c).union(d)) == 16:
		print a
		break
コード例 #29
0
def coprimes(*numbers):
    for p in utils.primes():
        if all(n % p == 0 for n in numbers): return False
        if all(n / p == 0 for n in numbers): return True  # stop searching
コード例 #30
0
prime.

Answer:
"""
from __future__ import print_function
from utils import timer, primes, take_n, is_prime
import itertools


ANSWER = None


def test_answer():
    if ANSWER is None:
        assert 0, 'Not Completed'
    else:
        assert ANSWER == main()


PRIMES = list(take_n(10000, primes()))
PRIMES_SET = frozenset(PRIMES)


@timer
def main():
    pass


if __name__ == '__main__':
    print(main())
コード例 #31
0
from __future__ import print_function
from utils import timer, primes
import itertools


ANSWER = 65537


def test_answer():
    if ANSWER is None:
        assert 0, 'Not Completed'
    else:
        assert ANSWER == main()


primes_l = set(itertools.islice(primes(), 10000))
square_sums = [2*(x**2) for x in range(40)]


@timer
def main():
    for n in itertools.count(3, 2):
        for p in primes_l:
            if p > n:
                break
            for s in square_sums:
                t = p + s
                if t == n:
                    break
            else:
                return n
コード例 #32
0
ファイル: problem69.py プロジェクト: snuderl/Project-euler
from utils import primes, memoize
primes = primes(10000000)
primeSet = set(primes)

@memoize
def factors(x):    
    if x in primeSet:
        return {x}
    t = x
    for i in primes:
        if t % i == 0:
            t = t / i
            break
    return {t, i} | factors(t)

###Calculates the number of relatively prime numbers up to x
@memoize
def phi(x):
    if x in primeSet:
        return x - 1.
    for p in primes:
        c = 0
        s = x
        if x % p == 0:
            while s % p == 0:
                c += 1
                s = s / p
            if c == 1:
                return phi(p) * phi(x / p)
            else:
                return phi(s * p) * (p ** (c - 1) * (p - 1))
コード例 #33
0
ファイル: 50.py プロジェクト: Cawb07/projecteulerstuff
from utils import is_prime, primes

consecutive_primes = []
total = 0
for prime in primes():
	total += prime
	if is_prime(total):
		consecutive_primes.append(prime)
	else:
		break
print consecutive_primes
コード例 #34
0
ファイル: 187.py プロジェクト: crazymerlyn/code
from utils import primes
from bisect import bisect_right

limit = 10**8

ps = list(primes(limit))

res = 0
for i, p in enumerate(ps):
    if p * p > limit: break
    x = limit / p
    if limit % p:
        j = bisect_right(ps, x)
    else:
        j = bisect_right(ps, x-1)
    res += j - i

print res
コード例 #35
0
ファイル: p043.py プロジェクト: ericdahl/project-euler
import itertools
import utils
primes = utils.primes(17)

def f(n):
    sn = str(n)
    for i in range(1, 8):
        if int(sn[i:i+3]) % primes[i - 1] != 0:
            return False
    return True

matches = []
for i in itertools.permutations('0123456789', 10):
    n = int(''.join(i))
    if f(n):
        matches.append(n)        

print matches
print sum(matches)
コード例 #36
0
from itertools import islice
from utils import primes

# https://docs.python.org/2/library/itertools.html#recipes
def nth(iterable, n, default=None):
    "Returns the nth item or a default value"
    return next(islice(iterable, n, None), default)

n = nth(primes(), 10000)

print(n)
コード例 #37
0
 def __float__(self):
     f = 1.0
     for (p, a) in zip(utils.primes(), self):
         f *= p**a
     return f
コード例 #38
0
ファイル: p041.py プロジェクト: ericdahl/project-euler
import utils

primes = utils.primes(7654321)

def p(n):
    sn = str(n)
    lsn = len(sn)

    if lsn > 10:
        return False
    
    return set([ int(d) for d in sn ]) == set(range(1, len(sn) + 1))


primes.reverse()
for prime in primes:
    if p(prime):
        print prime
        break


コード例 #39
0
def main():
    s = 0
    primes_larger_than_7 = dropwhile(lambda i: i<10, primes())
    print sum(take_11(truncatable_primes(primes_larger_than_7)))
コード例 #40
0
from utils import prime_cache, primes

LIMIT = 1_000_000
CACHE = prime_cache(LIMIT)
PRIMES = primes(LIMIT)


def compute():
    max_consec_count = 0
    max_consec_count_num = 0
    len_primes = len(PRIMES)
    for i in range(len_primes):
        consecutive_count = 1
        consecutive_sum = PRIMES[i]
        for j in range(i + 1, len_primes):
            consecutive_sum += PRIMES[j]
            consecutive_count += 1
            if consecutive_sum >= LIMIT:
                break
            elif consecutive_count > max_consec_count and CACHE[
                    consecutive_sum]:
                max_consec_count = consecutive_count
                max_consec_count_num = consecutive_sum
    return max_consec_count_num


if __name__ == "__main__":
    print(compute())
コード例 #41
0
ファイル: p027.py プロジェクト: ericdahl/project-euler
#
# It turns out that the formula will produce 40 primes for the consecutive values n=0 to 39
#
# howver, when n = 40, the result is not prime
# 
# n**2 - 79n + 1601 produces 80 consecutive primes for the consecutive values n=0 to 79. the produce of the coefficients -79 and 1601 is -126479
#
# considering quadratics of the  form n**2 + an + b where abs(a) < 1000 and abs(b) < 1000, find the product of the coefficients a and b for the quadratic expression which produces the maximum number of primes for consective values of n starting with 0

import utils


def f(b, c, n):
    return n**2 + b*n + c

primes = utils.primes(10000)

maximum = {'prime': 0}
for b in range(-1000, 1001):
    for c in range(-1000, 1001):
        #print b,c
        for n in xrange(0, 10000):
            res = f(b, c, n)
            if res not in primes:
                if n > maximum['prime']:
                    maximum['prime'] = n - 1
                    maximum['b'] = b
                    maximum['c'] = c
                break

print maximum
コード例 #42
0
from utils import primes
from utils import is_prime
from itertools import combinations

PRIMES = primes(10000)


def concat_prime(tuple):
    if len(tuple) != 2:
        raise AssertionError("concat_prime requires a tuple with 2 numbers")
    else:
        if is_prime(int(str(tuple[0]) + str(tuple[1]))) and is_prime(
                int(str(tuple[1]) + str(tuple[0]))):
            return True
        return False


def compute():
    prime_combos = combinations(PRIMES[1:], 2)  # 2 cannot be included
    return [v for v in prime_combos if concat_prime(v)][:10]


if __name__ == "__main__":
    print(compute())
コード例 #43
0
from utils import primes, is_prime

c = 0
s = 0
for p in primes():
    if p < 10:
        continue
    if c >= 11:
        break
    truncations = set([int(str(p)[:i]) for i in range(1, len(str(p)))] +
                      [int(str(p)[i:]) for i in range(1, len(str(p)))])
    if all(map(is_prime, truncations)):
        c += 1
        s += p
print(s)
コード例 #44
0
ファイル: 131.py プロジェクト: crazymerlyn/code
from utils import primes

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

count = 0
for a in range(1, 10000):
    b = a + 1
    p = b**3 - a**3
    if p > 10**6: break
    if p in ps:
        count += 1

print count
コード例 #45
0
ファイル: 146.py プロジェクト: crazymerlyn/code
def calc_mods(p):
    res = []
    for i in range(p):
        j = i * i % p
        for off in (1, 3, 7, 9, 13, 27):
            if (j + off) % p == 0:
                break
        else:
            res.append(i)
    return res


limit = 15 * 10**7
res = 0

mods = {p: calc_mods(p) for p in primes(500)}

for n in xrange(0, limit + 1, 210):
    for off in (10, 80, 130, 200):
        k = n + off
        possib = True
        for p in mods:
            if k * k > p and k % p not in mods[p]:
                possib = False
                break
        if not possib: continue
        k = (n + off)**2
        ps = []
        for j in range(k + 1, k + 28, 2):
            if isprime(j):
                ps.append(j)
コード例 #46
0
def main():
    for p in itertools.islice(utils.primes(), 10000, 10001):
        print p
コード例 #47
0
ファイル: p035.py プロジェクト: ericdahl/project-euler
import utils

primes = set(utils.primes(10**6))

def rotations(n):
    sn = str(n)
    return set([ int(sn[i:] + sn[:i]) for i in range(len(sn)) ])

print len(filter(lambda n: rotations(n).issubset(primes), primes.copy())) 
コード例 #48
0
ファイル: problem77.py プロジェクト: snuderl/Project-euler
	return inner


@memWays
def ways(n, nums):
	#print n, nums
	if not nums:
		return 0

	m = nums[0]
	if(m == n):
		return 1 + ways(n, nums[1:])
	elif(m < n):
		return ways(n - nums[0], nums) + ways(n, nums[1:])
	else:
		while True:
			nums = nums[1:n]
			if not nums:
				return 0
			elif(nums[0] >= n):
				return ways(n, nums)

from utils import primes
p = primes(100)
from time import time
start = time()
for x in range(1, len(p)):
	if ways(x, p) > 5000:
		print x
		break
print time() - start
コード例 #49
0
def main():
    guard = 2000000
    print sum(takewhile(lambda x: x<guard, primes()))
コード例 #50
0
from __future__ import print_function
from utils import timer, primes, is_permutation, take_between
from itertools import dropwhile, takewhile


ANSWER = 296962999629


def test_answer():
    if ANSWER is None:
        assert 0, 'Not Completed'
    else:
        assert ANSWER == main()


PRIMES_WITH_4_DIGITS = list(take_between(1000, 9999, primes()))


@timer
def main():
    for p1 in PRIMES_WITH_4_DIGITS:
        for p2 in PRIMES_WITH_4_DIGITS:
            if p2 <= p1:
                continue
            p3 = p2 + (p2 - p1)

            if p3 in PRIMES_WITH_4_DIGITS:
                if is_permutation(p1, p2) and is_permutation(p2, p3):
                    if p1 == 1487:
                        continue
                    return int(str(p1) + str(p2) + str(p3))
コード例 #51
0
from utils import primes

res = 0
for p in primes(10**8):
    if p < 5: continue
    res += (p - 3) * pow(8, p - 2, p) % p

print res
コード例 #52
0
def main():
    cnt = 0
    for p in itertools.takewhile(less_than_one_million, utils.primes()):
        if all(utils.is_prime(i) for i in rotated(p)):
            cnt += 1
    print cnt
コード例 #53
0
ファイル: problem-35.py プロジェクト: meetashok/projecteuler
def main():
    upper_limit = 1000000
    prime_numbers = utils.primes(upper_limit)

    return sum(
        [circular_prime(prime, prime_numbers) for prime in prime_numbers])
コード例 #54
0
def solve_0(N):
    return utils.primes(N)[-1]
コード例 #55
0
from utils import primes


def f(n, k):
    res = 0
    while n:
        res += n // k
        n //= k
    return res * k


n = 20000000
k = 15000000

res = 0
for p in primes(n):
    res += f(n, p) - f(k, p) - f(n - k, p)

print(res)
コード例 #56
0
ファイル: 266.py プロジェクト: crazymerlyn/code
def product(seq):
    res = 1
    for s in seq:
        res *= s
    return res


def muls(ps):
    res = []
    for i in range(len(ps) + 1):
        for comb in combinations(ps, i):
            res.append(product(comb))
    return sorted(res)


ps = list(primes(190))
n = len(ps)

left = muls(ps[:n // 2])
right = muls(ps[n // 2:])

ans = 0
limit = product(ps)**0.5
from bisect import bisect_left
for val in left:
    i = bisect_left(right, limit / val)
    if i:
        ans = max(ans, val * right[i - 1])
print(ans % 10**16)
コード例 #57
0
ファイル: p070.py プロジェクト: ericdahl/project-euler
import utils


def is_perm(a, b):
    return sorted(str(a)) == sorted(str(b))

best = (10000, 1)
primes = [ i for i in utils.primes(4000) if i > 2000 ]

for i in primes:
    for j in primes:
        n = i * j
        if n > 10**7:
            break
        phi = (i - 1) * (j - 1)
        ratio = (n * 1.0) / phi
        curr = (ratio, n)
        if is_perm(n, phi) and curr < best:
            best = curr

print best[1]
コード例 #58
0
def main(n=MILL*2):
    return sum(takewhile(lambda x: x < n, primes()))
コード例 #59
0
from utils import primes, is_prime as isprime
from collections import defaultdict

ps = primes(10**4)[1:]

concatenable = {p: set() for p in ps}

n = len(ps)

for p in ps:
    for q in ps:
        if isprime(int(str(p) + str(q))):
            concatenable[p].add(q)

for p in ps:
    for q in concatenable[p]:
        if q <= p: continue
        if p not in concatenable[q]: continue
        for r in concatenable[p] & concatenable[q]:
            if r <= q: continue
            if p not in concatenable[r] or q not in concatenable[r]: continue
            for s in concatenable[p] & concatenable[q] & concatenable[r]:
                if s <= r: continue
                if p not in concatenable[s] or q not in concatenable[
                        s] or r not in concatenable[s]:
                    continue
                for t in concatenable[p] & concatenable[q] & concatenable[
                        r] & concatenable[s]:
                    if t <= s: continue
                    if set([p, q, r, s]) <= concatenable[t]:
                        print p, q, r, s, t, p + q + r + s + t
コード例 #60
0
"""
from __future__ import print_function
from utils import timer, MILL, take_upto, primes


ANSWER = 997651


def test_answer():
    if ANSWER is None:
        assert 0, 'Not Completed'
    else:
        assert ANSWER == main()


PRIMES = list(take_upto(MILL, primes()))
PRIME_SET = set(PRIMES)
PRIME_SUMS = [PRIMES[0]]

# Calculate the cumaltive sum of primes for each step.
for psi, p in enumerate(PRIMES[1:]):
    PRIME_SUMS.append(PRIME_SUMS[psi] + p)


@timer
def main():
    # We use a sliding window to calculate the longest run and its associated
    # prime.
    psl = len(PRIME_SUMS)
    high_run = 0
    high_prime = 0