参考博客:
http://www.mathblog.dk/project-euler-37-truncatable-primes/
题目:
The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
Find the sum of the only eleven primes that are both truncatable from left to right and right to left.
NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
代码为:
- #coding=utf-8
- import math,time
- st=time.time()
- known={1:0,2:1,3:1,5:1,7:1}#0表示非质数,1表示质数
- def judge(n):
- if n in known:
- return known[n]==1
- if n==2:
- return 1
- else:
- success=1
- if n%2==0:
- success=0
- known[n]=success
- return success
- for x in range(3,int(math.sqrt(n)+1),2):
- if not n%x:
- success=0
- break
- known[n]=success
- return success
- def rightRotatePrime(nstr):
- success=True
- for index,value in enumerate(nstr):
- nstr=nstr[1:]
- if nstr and len(nstr)>0 and judge(int(nstr))==0:
- success=False
- break
- return success
- firstprime=['2','3','5','7']
- tempprime=[]
- relist=[]
- secondlist=['1','3','5','7','9']
- count,num=0,11
- relist=[]
- while count!=11:
- for item1 in firstprime:
- for item2 in secondlist:
- tempstr=item1+item2
- if judge(int(tempstr))==1:
- tempprime.append(tempstr)
- if rightRotatePrime(tempstr):
- relist.append(tempstr)
- count+=1
- if count==11:
- break
- firstprime=tempprime
- if count==11:
- break
- print relist
- li2=[ int(nstr) for nstr in relist]
- print sum(li2)
- #print sum(relist)
- print time.time()-st
['23', '37', '53', '73', '313', '317', '373', '797', '3137', '3797', '739397']
748317
0.00299978256226