簡體   English   中英

在 python 中查找低於給定數字的所有圓形素數

[英]Finding all circular prime numbers below a a given number in python

我需要編寫一個代碼來生成低於任何給定數字的所有循環素數。 我的代碼有一些缺陷,它沒有提供所有的循環素數,只是其中的幾個。 如果它們都低於我的給定數字,它只會顯示所有圓形素數。 例如,如果upper = 200,它將不顯示循環素數197。其他旋轉是971 和719。但是,如果upper = 1000,它將顯示所有3 個循環素數。 我不知道它是邏輯錯誤還是代碼錯誤,但我們感謝任何和所有幫助。

from collections import deque
def gen_primes(upper):

    D = {}
    q = 2
    while q <= upper:
        if q not in D:
            yield q
            D[q * q] = [q]
        else:
            for p in D[q]:
                D.setdefault(p + q, []).append(p)
            del D[q]       
        q += 1 

def circular_primes(upper):
    circular = []

    primes = list(gen_primes(upper-1))

    for prime in primes:
        string = str(prime)
        digits = deque(string)

        for rotation in range(1, len(string)):
            digits.rotate(1)

            if int("".join(digits)) not in primes:
                break
        else:
            circular.append(prime)

    return circular
print(circular_primes(150))

代碼修復

您沒有創建涵蓋所有可能旋轉的素數。

添加 function 計算大於 n 的最小數及其所有旋轉。

def next_largest(n):
  " For number n, returns number smallest number larger than all rotation of n "
  k = len(str(n))

  return 10**k

重構代碼

from collections import deque
def gen_primes(upper):

    D = {}
    q = 2
    while q <= upper:
        if q not in D:
            yield q
            D[q * q] = [q]
        else:
            for p in D[q]:
                D.setdefault(p + q, []).append(p)
            del D[q]       
        q += 1 

def next_largest(n):
   " For number n, returns number smallest number larger than all rotation of n "
  k = len(str(n))

  return 10**k

def circular_primes(upper):
    circular = []

    print(next_largest(upper))
    primes = list(gen_primes(next_largest(upper)))  # code mod

    for prime in primes:
        string = str(prime)
        digits = deque(string)

        for rotation in range(1, len(string)):
            digits.rotate(1)

            if int("".join(digits)) not in primes:
                break
        else:
            circular.append(prime)

    return circular

測試

print(circular_primes(200))

Output

[2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, 97, 113, 131, 197, 199, 311, 337, 373, 719, 733, 919, 971, 991]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM