码迷,mamicode.com
首页 > 其他好文 > 详细

EularProject 37:双向可截素数

时间:2015-07-30 13:43:24      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

Truncatable primes
Problem 37
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.
Answer:
748317
Completed on Thu, 30 Jul 2015, 03:54
定义一个左可截素数数组和右可截素数数组,每次从这两个数组中组合出位数加1的双向可截素数。由于这种方法初始的两个数组位数是1,因此只能从三位开始寻找,所以要把两位的找出来。两位的只需要从2,3,5,7中组合即可。

__author__ = ‘zhengyi‘
import math

def IsPrime(x):
    if x==1:
        return False
    k=int(math.sqrt(x))+1
    for i in range(2,k):
        if x%i==0:
            return False
    return True

elementSet=[1,2,3,5,7,9]
beginAdd1=[3,7]
endAdd1=[3,5,7]
beginAdd2=[]
endAdd2=[]
resultSet=[23,37,53,73]
numlen=0
while True:
    numlen+=1
    for i in elementSet:
        for item in beginAdd1:
            temp=i*pow(10,numlen)+item
            if IsPrime(temp):
                beginAdd2.append(temp)
        for item in endAdd1:
            temp=item*10+i
            if IsPrime(temp):
                endAdd2.append(temp)
    beginAdd1=beginAdd2
    beginAdd2=[]
    endAdd1=endAdd2
    endAdd2=[]
    if len(beginAdd1)==0 or len(endAdd1)==0:
        break
    for tail in beginAdd1:
        pub=tail//10
        for head in endAdd1:
            if head%pow(10,numlen)==pub:
                choose=head*10+tail%10
                if IsPrime(choose):
                    print(choose)
                    resultSet.append(choose)

print(sum(resultSet))

版权声明:本文为博主原创文章,未经博主允许不得转载。

EularProject 37:双向可截素数

标签:

原文地址:http://blog.csdn.net/zhangzhengyi03539/article/details/47146803

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!