Find the smallest prime which can be represented as sum of a prime and its reversal.
I am sure there is a far more efficient way to code the solution, but I'm still learning. :) First it creates a list of primes up to 10,000 (I assumed there'd be a solution in that range, otherwise I could increase n and run it again). Then it takes each prime, reverses it, adds them together and checks if the sum is prime and is lower than any other sums already found.
It produced the solution 241 + 142 = 383
n = 10000
primes = [2]
for i in range(3,n,2):
ptest = 0
for p in primes:
if p > i**0.5:
break
if i%p == 0:
ptest += 1
break
if ptest == 0:
primes.append(i)
summand = 0
sum = 10*n
for j in range(len(primes)):
if primes[j] > sum:
break
x = str(primes[j])
y = x[::-1]
s = int(x) + int(y)
if (s <= sum) and (s in primes):
sum = s
summand = x
print sum, summand
|
Posted by tomarken
on 2014-03-04 14:15:33 |