示例#1
0
def problem27():
    """
    Considering the quadratic formula n^2 + an + b where |a| < 1000 and
    |b| < 1000, find the product of the coefficients, a and b, for the
    quadratic expression that produces the maximum number of primes for
    consecutive values of n, starting with n = 0.
    """
    limit = 1000
    primes, primeset = util.primes(limit)

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

    max_n = 0
    max_coef = 0, 0
    for a in xrange(-1000, 1000):
        for b in primes:
            q = quad(a, b)
            n = 0
            while q(n) in primeset:
                n += 1
            if n > max_n:
                max_n = n
                max_coef = a, b
    return max_coef[0] * max_coef[1]
示例#2
0
def problem46():
    """
    It was proposed by Christian Goldbach that every odd composite number can
    be written as the sum of a prime and twice a square.

    9  = 7  + 2x1^2
    15 = 7  + 2x2^2
    21 = 3  + 2x3^2
    25 = 7  + 2x3^2
    27 = 19 + 2x2^2
    33 = 31 + 2x1^2

    It turns out that the conjecture was false.

    What is the smallest odd composite that cannot be written as the sum of
    a prime and twice a square?
    """
    limit    = 10000
    dsquares = [2*i*i for i in xrange(1, limit)]
    primes, primeset = util.primes(limit)

    def is_goldbach(i):
        for p in primes:
            if p > i:
                return False
            for ds in dsquares:
                if i == p + ds:
                    return True
                elif i < p + ds:
                    break
        return False

    for i in xrange(3, limit, 2):
        if i not in primeset and not is_goldbach(i):
            return i
示例#3
0
def problem49():
    """
    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?
    """
    limit = 10000
    primes, primeset = util.primes(limit)

    for a in primes:
        permset = set([int(x) for x in util.permutations(str(a))])
        for b in util.permutations(str(a)):
            b = int(b)
            if b > a and b in primeset:
                c = b + (b-a)
                if c in primeset and c in permset and c != 8147:
                    return "{}{}{}".format(a, b, c)
示例#4
0
def problem35():
    """
    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?
    """
    limit = 1000000
    primes, primeset = util.primes(limit)

    def rotations(digits):
        for i in xrange(len(digits)):
            yield digits[i:] + digits[:i]

    count = 0
    for i in xrange(2, limit):
        if i in primeset:
            for p in rotations(str(i)):
                if int(p) not in primeset:
                    break
            else:
                count += 1
    return count
示例#5
0
def problem10():
    """
    The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

    Find the sum of all the primes below two million.
    """
    limit = 2000000
    primes, primeset = util.primes(limit)
    return sum(primes)
示例#6
0
def solve():
    m = [0, 0, 0]

    def max_prime(a, b):
        c = count_prime(a, b)
        if c > m[0]:
            m[0] = c
            m[1] = a
            m[2] = b

    pa = primes()
    a = pa.next()
    while a < 1000:
        pb = primes()
        b = pb.next()
        while b < 1000:
            max_prime(a, b)
            max_prime(a, -b)
            max_prime(-a, -b)
            max_prime(-a, b)
            b = pb.next()
        a = pa.next()
    return m
示例#7
0
def solve():
    print 'start'
    s = 0
    p = primes()
    n = p.next()
    cd = 11
    while cd > 0:
        if n < 11:
            n = p.next()
            continue
        if is_removeable_prime(n):
            print n
            cd -= 1
            s += n
        n = p.next()
    return s
示例#8
0
def problem50():
    """
    Which prime, below one-million, can be written as the sum of the most
    consecutive primes?
    """
    limit = 1000000
    primes, primeset = util.primes(limit)

    best = (1, 1)
    for i in xrange(len(primes)):
        total = 0
        for j in xrange(i, len(primes)):
            total += primes[j]
            if total >= limit:
                break
            elif total in primeset and j-i > best[1]:
                best = total, j-i
    return best[0]
示例#9
0
def problem47():
    """
    The first two consecutive numbers to have two distinct prime factors are:

    14 = 2 x 7
    15 = 3 x 5

    The first three consecutive numbers to have three distinct prime factors are:

    644 = 2^2 x 7 x 23
    645 = 3 x 5 x 43
    646 = 2 x 17 x 19.

    Find the first four consecutive integers to have four distinct prime factors.
    What is the first of these numbers?
    """
    limit = 1000000
    fcount = 4
    primes, primeset = util.primes(limit)

    i = 3
    count = 0
    while i < limit:
        j = i
        factors = set()
        while j not in primeset:
            for p in primes:
                if p > 1 and j % p == 0:
                    factors.add(p)
                    j /= p
                    break
        factors.add(j)

        if len(factors) != fcount:
            count = 0
        else:
            count += 1

        if count == fcount:
            return i - fcount + 1

        i += 1
示例#10
0
def solve():
    """
    The n/phi(n) will be large when phi(n) is small and n is large. To make
    phi(n) small, we have to make n have as many divisors as possible. A good
    way to do this is to include small primes as some of its divisors.
    Multiples of these small primes will be ruled out from the totient, which
    is a good thing.  Not guaranteed to be the right answer, I suppose, but
    turns out to be.
    """
    primes = util.primes(1000000)
    product = 1
    phi = 0
    for p in primes:
        if product * p <= 1000000:
            print "multiplying one more prime:", p
            product *= p
            phi += 1
        else:
            break
    print "final n:", product
    print "phi(n):", phi
    print "n/phi(n):", product/float(phi)
示例#11
0
def problem37():
    """
    Find the sum of the only eleven primes that are both truncatable from
    left to right and right to left.
    """
    limit = 1000000
    total = 0
    primes, primeset = util.primes(limit)

    def is_truncatable(i):
        left = right = str(i)
        while len(left) > 0 and len(right) > 0:
            if int(left) not in primeset or int(right) not in primeset:
                return False
            else:
                left, right = left[1:], right[:-1]
        return True

    for i in xrange(11, limit, 2):
        if is_truncatable(i):
            total += i
    return total
示例#12
0
def p50():
    """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?
    """
    p = primes(999999)
    work = p[:]
    pSet = set(p)
    bestPrime = 2
    for i in range(1,len(work)):
        for j in range(len(work)-i):
            work[j]+=p[j+i]
            if work[j] > 999999:
                break
            if work[j] in pSet:
                bestPrime = work[j]
                print bestPrime
    print bestPrime
示例#13
0
"""Which prime, below one-million, can be written as the sum of the most
consecutive primes?
"""
from util import primes

def IsPrime(n):
  for d in xrange(2, int(n**0.5) + 1):
    if n%d == 0: return False
  return True

MAX = 1000000
memo = []
(pp, pl) = (0, 0)
for p in primes(MAX):
  if p == 2:
    memo.append(p)
    continue
  i = 0
  while i < len(memo):
    memo[i] += p
    if memo[i] > MAX: break
    else:
      if IsPrime(memo[i]):
        if i > pl:
          pl = i
          pp = memo[i]
      i += 1
  else:
    memo.insert(0, p)
    continue
  break
示例#14
0
文件: 069.py 项目: jag426/euler
from util import primes

product = 1
for p in primes():
    next = product * p
    if next > 10**6:
        break
    product = next
print(product)
示例#15
0
from util import primes
for nth, prime in enumerate(primes()):
    if nth == 10000:
        print(prime)
        break
示例#16
0
文件: p50.py 项目: andermic/euler
#! /usr/bin/python

from util import primes
from util import inb
p = primes(1000000)

s = []
res = 21
for i in range(len(p)):
    s.append(sum(p[i:i+res]))
    if s[i] > 1000000:
        break

while s != []:
    res += 2
    for i in range(len(s)):
        s[i] += p[i+res-1] + p[i+res-2]
        if s[i] > 1000000:
            s = s[:i]
            break
        if inb(s[i],p):
            print s[i],res
示例#17
0
#! /usr/bin/python

from util import primes
from util import inb
p = primes(1000000)

s = []
res = 21
for i in range(len(p)):
    s.append(sum(p[i:i + res]))
    if s[i] > 1000000:
        break

while s != []:
    res += 2
    for i in range(len(s)):
        s[i] += p[i + res - 1] + p[i + res - 2]
        if s[i] > 1000000:
            s = s[:i]
            break
        if inb(s[i], p):
            print s[i], res
示例#18
0
import psyco
import util

primes = util.primes(9999)
primes_set = set(util.primes(99999999))

# pass 1: pairs
print "pairs"
conc_pairs = set()
for p1 in primes:
    for p2 in reversed(primes):
        if p1 < p2:
            p1str = str(p1)
            p2str = str(p2)
            if int(p1str+p2str) in primes_set and\
               int(p2str+p1str) in primes_set:
                   conc_pairs.add((p1,p2))
        else:
            break
print conc_pairs

# pass 2: triples
print "triples"
conc_triples = set()
for p1,p2 in conc_pairs:
    for p3 in reversed(primes):
        if p2 < p3:
            if (p1,p3) in conc_pairs and\
               (p2,p3) in conc_pairs:
                   conc_triples.add((p1,p2,p3))
        else:
示例#19
0
文件: q10.py 项目: aelred/euler
from util import primes

if __name__ == '__main__':
    print(sum(primes(2000000)))
示例#20
0
def first_prime_factor(n):
    for prime in primes():
        if n % prime == 0:
            return prime
示例#21
0
文件: 051.py 项目: jag426/euler
from util import is_prime, primes

pg = primes()
while next(pg) <= 56003:
    pass
answer = None
for p in pg:
    s = str(p)
    for d in range(3):
        if str(d) in s:
            n = 1
            for e in range(d+1, 10):
                if is_prime(int(s.replace(str(d), str(e)))):
                    n += 1
            if n >= 8:
                answer = p
                break
    if answer:
        break
print(answer)
示例#22
0
文件: q7.py 项目: aelred/euler
from util import primes

if __name__ == '__main__':
    size = 2 ** 16

    while True:
        ps = list(primes(size))

        try:
            print(ps[10000])
        except IndexError:
            size *= 2
        else:
            break
示例#23
0
文件: p69.py 项目: andermic/euler
#! /usr/bin/python
from util import primes

product = 1
for i in primes(20):
    product *= i
    if product > 10 ** 6:
        print product / i
示例#24
0
文件: q517.py 项目: aelred/euler
import math

from util import primes


def g(a, x):
    y_max = math.ceil(x / a - 1) + 1

    mem = [1] * (y_max+1)

    z_start = math.floor(x - a)

    for z in range(z_start, -1, -1):
        y_start = math.floor((x - z) / a - 1)

        for y in range(y_start, -1, -1):
            mem[y] += mem[y+1]

    return mem[0]


def G(n):
    return g(n ** 0.5, n)


if __name__ == '__main__':
    all_primes = primes(start=10000000, end=10010000)
    summed = sum([G(p) for p in all_primes])
    print(summed % 1000000007)
示例#25
0
"""What is the 10001st prime number?
"""
from util import primes

print[p for p in primes(10001)][-1]
示例#26
0
import psyco
import util

primes = set(util.primes(1000000))

def left_right(p):
    s = str(p)
    for i in range(len(s)):
        yield int(s[i:])

def right_left(p):
    s = str(p)
    for i in range(1, len(s)+1):
        yield int(s[:i])


def all_prime(l):
    return all(p in primes for p in l)

if __name__ == "__main__":
    sum = 0
    num = 0
    for p in primes:
        if p not in [2,3,5,7]:
            if all_prime(left_right(p)) and all_prime(right_left(p)):
                sum += p
                num += 1
    print "found:", num
    print "sum:", sum
示例#27
0
def problem_7():
	return last(primes(10001))
示例#28
0
文件: e0007.py 项目: eykd/euler
def primes_test():
    p = 0
    for prime in primes(max_step=6):
        p = prime

    assert_equal(p, 13)
示例#29
0
from collections import deque
from itertools import takewhile, imap
from operator import itemgetter

from util import primes


print deque(
    imap(itemgetter(1),
         takewhile(lambda (i, v): i < 10001, enumerate(primes()))),
    maxlen=1).pop()
示例#30
0
文件: e0007.py 项目: eykd/euler
def main():
    p = 0
    for prime in primes(max_step=10001):
        p = prime
    return p
示例#31
0
文件: 72.py 项目: andermic/euler
If we list the set of reduced proper fractions for d <= 8 in ascending order of size, we get:

1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8

It can be seen that there are 21 elements in this set.

How many elements would be contained in the set of reduced proper fractions for d <= 1,000,000?
"""

# return int(n * reduce(lambda x,y: x*y, [1-(1./i) for i in pfact]))

from util import inb, pf, primes, totient
from math import sqrt

end = 10 ** 6
ps = primes(end)
ps_sq = primes(int(sqrt(end)))
pfacts = {}

# print ps, inb(2, ps)
for i in xrange(2, end + 1):
    if inb(i, ps) != -1:
        pfacts[i] = (set([i]), i - 1)
    else:
        for prime in ps_sq:
            if i % prime == 0:
                pf, totient = pfacts[i / prime]
                if prime in pf:
                    pfacts[i] = (pf, totient * prime)
                else:
                    pfacts[i] = (pf.union(set([prime])), totient * (prime - 1))
示例#32
0
文件: p60.py 项目: andermic/euler
#! /usr/bin/python

from util import primes, is_prime, inb

MAX = 2000
LIST_LENGTH = 5
PRIMES_TO = 10**6

print "Computing first %d primes..." % PRIMES_TO
p = primes(PRIMES_TO)
print "Done\n"

pair_dict = {}

# Use a simple recursive backtracking algorithm
def solve(cur_list):
	print cur_list
	if len(cur_list) == LIST_LENGTH:
		print cur_list, sum(cur_list)
		exit()
	start = 1 if cur_list == [] else inb(cur_list[-1], p) + 1
	for i in p[start:MAX]:
		recurse = True
		for j in cur_list:
			pairing = int(str(j) + str(i))
			if pair_dict.get(pairing) != None:
				recurse = False
				break
		if recurse:
			solve(cur_list + [i])