Exemplo n.º 1
0
def circular_primes(maximum):
    # Immediately Filter out all prime numbers greater than 2 that contain an
    # even digit, since at least one of their rotations won't be prime
    primes = filter(lambda p: p == 2 or non_even(p),
                    takewhile(lambda p: p < maximum, common.primes()))

    return [p for p in primes if all(n in primes for n in rotations(p))]
Exemplo n.º 2
0
def sum_of_primes_below(n: int) -> int:
    """
    Returns the sum of all of the prime integers that are less than n.

    >>> sum_of_primes_below(10)
    17
    """
    return sum(itertools.takewhile(lambda x: x < n, primes()))
Exemplo n.º 3
0
def concise_factors(factors):
  result = []
  for p in common.primes():
    assert p <= factors[0]
    result.append(0)
    while factors and factors[0] == p:
      result[-1] += 1
      factors.pop(0)
    if not factors: return tuple(result)
Exemplo n.º 4
0
def nth_prime(n: int) -> int:
    """
    Returns the nth prime integer.

    >>> nth_prime(1)
    2
    >>> nth_prime(6)
    13
    """
    return next(itertools.islice(primes(), n - 1, None))
Exemplo n.º 5
0
def factorize(n):
    factors = []

    if n > 1:
        for p in common.primes():
            while n % p == 0:
                factors.append(p)
                n = n / p

            if n == 1:
                break

    return factors
Exemplo n.º 6
0
def solution():
    # Note: same method as problem 108
    threshold = 4*10**6

    # Get the maximum number of primes that would be required to find the least
    # value of `n` (using the same reasoning as that of the distinct()
    # function)
    factors = list(islice(primes(), 0, log(threshold, 2) + 1))

    # Order the prime factors, and add terms with multiplicities greater than
    # 1 that are smaller than the largest retrieved prime
    factors = sorted([(p**i, p, i)
                      for p in factors
                      for i in takewhile(lambda n: p**n <= max(factors),
                                         count(1))])

    # Prime factorization mapping for potential results, producing strictly
    # increasing values (before minimization)
    least = {}

    results = []

    for idx, (_, p, i) in enumerate(factors):
        # Increase the multiplicity of p
        least[p] = i

        if distinct(least) > threshold:
            # Make a new copy of the factorization dictionary before the
            # minimization process
            result = dict(least.items())

            # Keep track of prime factors whose multiplicity has been finalized
            checked = set()

            for _, prime, _ in reversed(factors[:idx]):
                if prime in checked:
                    continue

                # Attempt reducing the multiplicity of `prime`...
                result[prime] -= 1

                # ... and backtrack if necessary
                if distinct(result) <= threshold:
                    result[prime] += 1

                    # Finalize `prime`'s multiplicity
                    checked.add(prime)

            results.append(product(b**e for b, e in result.items()))

    return min(results)
Exemplo n.º 7
0
def solution():
    pgroups = {}

    for p in takewhile(lambda p: p < 10000,
                       dropwhile(lambda p: p < 1000, primes())):

        pgroups.setdefault(''.join(sorted(str(p))), []).append(p)

    for plist in pgroups.values():
        if len(plist) >= 3:
            for pcombo in combinations(plist, 3):
                a, b, c = pcombo
                if a - b == b - c:
                    return ''.join(map(str, pcombo))
Exemplo n.º 8
0
def solution():
    iprimes = primes()

    for n in count(5):
        pgroups = {}

        # Check all n-digit primes
        for p in takewhile(lambda p: p < 10**n,
                           dropwhile(lambda p: p < 10**(n-1), iprimes)):
            for k in keys(p):
                pgroups.setdefault(k, []).append(p)

        for key, plist in sorted(pgroups.items()):
            if len(plist) == 8:
                return (key, min(plist))[1]
Exemplo n.º 9
0
def admissible(limit):
    def partial(n, maxfactor, ps):
        if n >= limit:
            return

        yield n

        ps0, ps1 = tee(ps)
        res0 = partial(n*maxfactor, maxfactor, ps0)

        nextp = next(ps1)
        res1 = partial(n*nextp, nextp, ps1)

        for a in coalesce(res0, res1):
            yield a

    ps = primes()
    first = next(ps)
    return partial(first, first, ps)
Exemplo n.º 10
0
def solution():
    base = 1000

    # Keep the same iterator throughout to pull more prime values whenever
    # necessary
    iprimes = primes()

    # Use a set for quick prime lookups
    pset = set()

    for i in count():
        limit = base*(10**i)

        pset.update(takewhile(lambda p: p < limit, iprimes))

        tuples = set((p,) for p in pset)

        for j in range(2, 6):
            new_tuples = set()

            for ts in combinations(tuples, 2):
                t = tuple(sorted(set([e for t in ts for e in t])))

                if len(t) != j:
                    continue

                for a, b in permutations(t, 2):
                    n = int(str(a) + str(b))

                    if n < limit:
                        if n not in pset:
                            break
                    elif not is_prime(n):
                        break
                else:
                    new_tuples.add(t)

            tuples = new_tuples

        if tuples:
            return min((sum(t), t) for t in tuples)
Exemplo n.º 11
0
def solution():
    # Initial number of primes to fetch
    fetch = 1000

    # Keep the same iterator throughout to pull more prime values whenever
    # necessary
    iprimes = primes()

    # Use a set for quick prime lookups
    pset = set()

    # Skip the given examples
    start = 647

    # Number of consecutive numbers to have 4 distinct prime factors
    consecutive4 = 0

    while True:
        pset.update(islice(iprimes, 0, fetch))

        stop = max(pset) + 1

        for n in range(start, stop):
            if n not in pset:
                if len([1 for d in divisors(n) if d in pset]) == 4:
                    consecutive4 += 1

                    if consecutive4 == 4:
                        return n - 3

                    continue

            consecutive4 = 0

        start = stop

        # Triple the number of available primes
        fetch *= 2
Exemplo n.º 12
0
def solution():
    pset = set(takewhile(lambda p: p < 1e6, primes()))

    # Minimum number of consecutive primes summing to a prime < 1e6, using the
    # provided examples
    minc = 21

    # Plausible upper bound on the primes that will be part of the sum
    max_prime = 10**6 / (minc - 1)

    psubset = sorted([p for p in pset if p < max_prime])

    # Using the smallest (first) primes, compute an upper bound on the number
    # of consecutive primes that can sum up to < 1e6
    maxc, _ = deque(takewhile(lambda t: t[1] < 1e6,
                              ((i, sum(psubset[:i]))
                               for i in range(1, len(psubset) + 1))),
                    maxlen=1).pop()

    for length in range(maxc, minc, -1):
        for i in range(len(psubset) - length):
            s = sum(psubset[i:i+length])
            if s in pset:
                return s
Exemplo n.º 13
0
def solution():
    return sum(takewhile(lambda n: n < 2e6, common.primes()))
Exemplo n.º 14
0
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

# What is the 10 001st prime number?

from common import primes, take

print(list(take(10001, primes()))[-1])
Exemplo n.º 15
0
(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 common
import itertools

useful_primes = set(
  p for p in itertools.takewhile(lambda x: x < 10**4,
                                 itertools.dropwhile(lambda x: x < 10**3,
                                                     common.primes())))

def euler049():
  for i in useful_primes:
    if i == 1487: continue  # skip known solution
    for j in useful_primes:
      if i >= j: continue
      if sorted(str(i)) != sorted(str(j)): continue
      k = j + (j - i)
      if k not in useful_primes: continue
      if sorted(str(i)) != sorted(str(k)): continue
      return int('%d%d%d' % (i,j,k))

common.submit(euler049(), expected=296962999629)
from common import primes

print sum(primes(2000000))
Exemplo n.º 17
0
def sum_primes_below(n):
    return sum(itertools.takewhile(lambda x: x < n, common.primes()))
Exemplo n.º 18
0
(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 common
import itertools

useful_primes = set(p for p in itertools.takewhile(
    lambda x: x < 10**4,
    itertools.dropwhile(lambda x: x < 10**3, common.primes())))


def euler049():
    for i in useful_primes:
        if i == 1487: continue  # skip known solution
        for j in useful_primes:
            if i >= j: continue
            if sorted(str(i)) != sorted(str(j)): continue
            k = j + (j - i)
            if k not in useful_primes: continue
            if sorted(str(i)) != sorted(str(k)): continue
            return int('%d%d%d' % (i, j, k))


common.submit(euler049(), expected=296962999629)
Exemplo n.º 19
0
#!/usr/bin/env python

from common import is_prime, primes

MAX = 1000000
pnums = set(primes(MAX))


def rotations(num):
    s = str(num)
    return [int(s[i:] + s[:i]) for i in range(len(s))]


def is_cicrular(num):
    return all([a in pnums for a in rotations(num)])


circulars = len(list(filter(is_cicrular, pnums)))

print(circulars)
Exemplo n.º 20
0
    i = 3
    while i < n:
        if not is_prime(i):
            yield i

        i += 2


def squares(n=10000000):
    """ Find squares below n """

    i = 1
    while True:
        sq = i**2
        if sq > n:
            break

        yield sq
        i += 1


for oc in odd_composites():
    for p in primes(oc - 1):
        diff = oc - p
        sq = list(squares((diff) // 2))
        if (diff // 2) in sq:
            break
    else:
        print("not found when odd is {}".format(oc))
        break
Exemplo n.º 21
0
def value(n):
  # assert isinstance(n, tuple)
  return common.product(p**c for p,c in zip(common.primes(), n))  
Exemplo n.º 22
0
def candidate_bs():
    """
    Returns all possible values for the coefficient b, using the fact that b
    must be prime for there to be a consecutive sequence of generated primes
    """
    return takewhile(lambda p: p < MAX_MODULUS, common.primes())
Exemplo n.º 23
0
def solution():
    return next(islice(primes(), 10000, None))
Exemplo n.º 24
0
def sum_primes_below(n):
  return sum(itertools.takewhile(lambda x: x < n,
                                 common.primes()))
Exemplo n.º 25
0
#!/usr/bin/env python

from itertools import count
from common import primes

MAX = 2000000

s = sum(a for a in primes(MAX))

print(s)
Exemplo n.º 26
0
#!/usr/bin/env python

from common import primes

MAX = 1000000
pnums = set(p for p in primes(MAX))


def get_combinations(n):
    o = set()
    s = str(n)
    for a in range(len(s) - 1):
        o.add(int(s[a + 1:]))
        o.add(int(s[:a + 1]))

    return (o)


def are_combs_prime(n):
    return all([a in pnums for a in get_combinations(n)])


truncatable_primes = filter(are_combs_prime, (p for p in pnums if p > 9))

print(sum(truncatable_primes))
Exemplo n.º 27
0
# set of divisors
# start with 2520, count up
# or, start with 2520 and multiply by all the remaining divisors? 
# 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
# list of odd numbers, also 2?

from common import primes

full_set = range(1, 21)
test = []
temp= []
divisors = []
answer = 1

for x in full_set:
	test = primes(x)
	temp = divisors[:]
	for y in test:
		if y in temp:
			temp.remove(y)
		else:
			divisors.append(y)
	print x, divisors

for x in divisors:
	answer *= x

print answer 

# def check_divisors(number):
# 	divisors = xrange(1, 11)