问题陈述:
这个数字197被称为循环素数,因为数字的所有旋转:197、971和719本身都是素数。
100以下有13个这样的素数:2、3、5、7、11、13、17、31、37、71、73、79和97。
一百万以下有多少个循环素数?
我的问题
我检查了所有代码,发现二进制搜索函数给出了一个return 1语句作为输出打印成功。但最终名单上什么都没有。请帮忙
Python中的程序:

from time import time
start = time()
LIMIT = 1000000   # largest limit of the prime numbers
prima = []   # list of primes later to be filled by primes function

# binary search function
def Bsearch(lsta,low,high,search):
        if low>high:
                return -1
        else:
            mid = int((low+high)/2)
            if search<lsta[mid]:
                Bsearch(lsta,low,mid-1,search)
            elif search>lsta[mid]:
                Bsearch(lsta,mid+1,high,search)
            elif search==lsta[mid]:
                print("Success!")
                return 1

# prime number generating function
# uses sieve of Era** algorithm
# produces correct result tested
def primes(LIMIT):
    lsta = {}  # temporaty empty dictionary
    for i in range(2,LIMIT):
        lsta[i] = 1
    for i in range(2,LIMIT):
        for j in range(i,LIMIT):
            if i*j>LIMIT:
                break
            lsta[i*j] = 0
    for i in range(2,LIMIT):
        if(lsta[i]==1):
            prima.append(i)
primes(LIMIT)

final = []
for item in prima:
    x = int(str(item)[::-1])
    # real problem here the following statement not inserting any value in final list
    if(Bsearch(prima,0,len(prima)-1,x)):
        print("Hello!")
        print(final)
        final.append(item)
print(final)

最佳答案

快速生成prime numberslist out Circular Prime numbers

def primes(max_n):
    numbers = range(3, max_n+1, 2)
    half = (max_n)//2
    initial = 4
    for step in xrange(3, max_n+1, 2):
        for i in xrange(initial, half, step):
            numbers[i-1] = 0
        initial += 2*(step+1)

        if initial > half:
            return [2] + filter(None, numbers)


def rotate(S_list):
    S=[]
    for i in range(len(S_list)):
        S.append(int(S_list[i:]+S_list[:i]))
    return set(S)

def circularPrime(limit):
    All_primes_in_limit = primes(limit)
    circular_prime=[]
    reject_list=['0','2','4','5','6','8']
    All_primes_in_limit=[i for i in All_primes_in_limit if not any(j in reject_list for j in set(str(i)))]
    while All_primes_in_limit:
        ShufleSet=rotate(str(All_primes_in_limit[-1]))
        PrimesSet=set(All_primes_in_limit)
        if not ShufleSet -  PrimesSet:
            circular_prime+=list(ShufleSet)
        All_primes_in_limit=list(PrimesSet-ShufleSet)
    circular_prime.sort()
    return circular_prime


#for limit value 1000000
print circularPrime(1000000)

这是循环素数列表的最快算法

关于python - 圆素数不正确的输出Python程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22738065/

10-15 19:25