Python Implementation of Problem 49

View source code here on GitHub!

Includes

Problem Solution

Project Euler Problem 49

I was surprised how fast my brute-force solution went, but it worked

Problem:

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?

python.src.p0049.main() int
 1"""
 2Project Euler Problem 49
 3
 4I was surprised how fast my brute-force solution went, but it worked
 5
 6Problem:
 7
 8The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases
 9by 3330, is unusual in two ways: (i) each of the three terms are prime, and,
10(ii) each of the 4-digit numbers are permutations of one another.
11
12There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes,
13exhibiting this property, but there is one other 4-digit increasing sequence.
14
15What 12-digit number do you form by concatenating the three terms in this
16sequence?
17"""
18from itertools import takewhile, tee
19
20from .lib.iters import consume, digits
21from .lib.primes import primes
22
23
24def main() -> int:
25    primes_at_1000 = primes(10000)
26    consume(takewhile((1000).__gt__, primes_at_1000))
27    primes_at_1000, pgen_1 = tee(primes_at_1000)
28    for p1 in pgen_1:
29        if p1 == 1487:
30            continue
31        pgen_1, pgen_2 = tee(pgen_1)
32        for p2 in pgen_2:
33            if p2 > 10000 - p1 // 2:
34                break
35            pgen_2, pgen_3 = tee(pgen_2)
36            for p3 in pgen_3:
37                if p1 - p2 < p2 - p3:
38                    continue
39                elif p1 - p2 > p2 - p3:
40                    break
41                elif set(digits(p1)) == set(digits(p2)) == set(digits(p3)):
42                    return p1 * 10**8 + p2 * 10**4 + p3
43    return -1  # pragma: no cover

Tags: arithmetic-progression, prime-number, permutation, python-iterator