No_37

参考博客:

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.


代码为:

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #coding=utf-8  
  2. import math,time  
  3. st=time.time()  
  4. known={1:0,2:1,3:1,5:1,7:1}#0表示非质数,1表示质数  
  5. def judge(n):  
  6.     if n in known:  
  7.         return known[n]==1  
  8.     if n==2:  
  9.         return 1  
  10.     else:  
  11.         success=1  
  12.         if n%2==0:  
  13.             success=0  
  14.             known[n]=success  
  15.             return success  
  16.         for x in range(3,int(math.sqrt(n)+1),2):  
  17.             if not n%x:  
  18.                 success=0  
  19.                 break  
  20.         known[n]=success  
  21.         return success  
  22. def rightRotatePrime(nstr):  
  23.     success=True  
  24.     for index,value in enumerate(nstr):  
  25.         nstr=nstr[1:]  
  26.         if nstr and  len(nstr)>0 and  judge(int(nstr))==0:  
  27.             success=False  
  28.             break  
  29.     return success  
  30.   
  31.   
  32. firstprime=['2','3','5','7']  
  33. tempprime=[]  
  34. relist=[]  
  35. secondlist=['1','3','5','7','9']  
  36. count,num=0,11  
  37. relist=[]  
  38. while count!=11:  
  39.     for item1 in firstprime:  
  40.         for item2 in secondlist:  
  41.             tempstr=item1+item2  
  42.             if judge(int(tempstr))==1:  
  43.                 tempprime.append(tempstr)  
  44.                 if rightRotatePrime(tempstr):  
  45.                     relist.append(tempstr)  
  46.                     count+=1  
  47.                     if count==11:  
  48.                         break  
  49.         firstprime=tempprime  
  50.         if count==11:  
  51.             break  
  52.   
  53. print relist  
  54. li2=[ int(nstr) for nstr in relist]  
  55. print sum(li2)  
  56. #print sum(relist)  
  57. print  time.time()-st  
运行结果为:
['23', '37', '53', '73', '313', '317', '373', '797', '3137', '3797', '739397']
748317
0.00299978256226
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值