Back to Project Euler

Previous Problem Next Problem

Problem 49: Prime Permutations

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?

Solution

I first identify which primes are permutations of each other by assigning each a "key" of their digits in sorted order, then using Python's "dict" structure to collect all primes with the same key. Once that's done, I analyze each triple of primes \(p_i < p_j < p_k\) with the same key, and see which triple besides the given one satisfies \(p_i + p_k = 2p_j\).

Python Code

from sympy import primerange
def p49():
	D = dict()
	for p in primerange(1000, 10000):
		key = ''.join(sorted(str(p)))
		if key in D:
			D[key].append(p)
		else:
			D[key] = [p]
	for key in D:
		if key == '1478':
			continue
		for i in range(len(D[key])-2):
			for j in range(i+1, len(D[key])-1):
				for k in range(j+1, len(D[key])):
					if D[key][i] + D[key][k] == 2 * D[key][j]:
						return str(D[key][i]) + str(D[key][j]) + str(D[key][k])

Previous Problem Next Problem

Back to Project Euler