Project Euler
Problem 49(Prime permutations)
(이경수)
2019. 8. 16. 17:46
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?
In Python:
import time
import math
def seive(n):
i = 2
primecodeList =[1 for i in range(1, n + 1)]
primecodeList[0] = 0
primeList = []
while i < n + 1:
if primecodeList[i - 1] == 1:
primeList.append(i)
for j in range(2, n // i + 1):
primecodeList[i * j - 1] = 0
i += 1
return primeList
def ispermutation(i, j, k):
stri = sorted(str(i))
strj = sorted(str(j))
strk = sorted(str(k))
if stri == strj and strj == strk:
return True
startTime = time.time()
primeList = []
for prime in seive(10 ** 4):
if math.log10(prime) > 3:
primeList.append(prime)
for i in range(0, len(primeList)):
for k in range(0, i):
j = (primeList[i] + primeList[k]) // 2
if j in primeList and ispermutation(primeList[i], j, primeList[k]):
print(str(primeList[k]) + str(j) + str(primeList[i]))
print(time.time() - startTime, "seconds")
Run time: 8.202334880828857 seconds
In Python:
import time
import math
def seive(n):
i = 2
primecodeList =[1 for i in range(1, n + 1)]
primecodeList[0] = 0
primeList = []
while i < n + 1:
if primecodeList[i - 1] == 1:
for j in range(2, n // i + 1):
primecodeList[i * j - 1] = 0
if math.log10(i) > 3:
primeList.append(i)
i += 1
return primeList
def ispermutation(i, j):
stri = sorted(str(i))
strj = sorted(str(j))
if stri == strj:
return True
startTime = time.time()
primeList = seive(10 ** 4)
for i in range(0, len(primeList)):
for k in range(0, i):
if ispermutation(primeList[i], primeList[k]):
j = (primeList[i] + primeList[k]) // 2
if j in primeList and ispermutation(primeList[i], j):
print(str(primeList[k]) + str(j) + str(primeList[i]))
print(time.time() - startTime, "seconds")
Run time: 0.8857400417327881 seconds
Solution: 296962999629