簡體   English   中英

測試素數的更短方法

[英]Shorter way to test if prime number

為了測試一個數字是否是素數,我這樣做:

def isprime(n):

    if n < 2: return False

    for i in range(2, n):
        if n % i == 0:
            return False
    else:
        return True

我想知道如何使編寫更有效/更短。

帶發電機:

def isprime(n):
    return (all(False for i in range(2,n) if n % i == 0) and not n < 2)
    
print (isprime(0))
print (isprime(1))
print (isprime(2))
print (isprime(3))
print (isprime(9))
print (isprime(10))
print (isprime(13))

Output:

False
False
True
True
False
False
True

除了@Théophile 的建議,我還要添加以下建議:

  1. 在調用 is_prime 之前測試一個數字是否為偶數且大於 2(無需調用is_prime )。

  2. 代替range(2, n) ,使用range(3, n, 2) 這將只考慮奇數; range的第三個參數是遞增的步長。

  3. 與其循環遍歷小於 n 的平方根的所有整數(或所有奇數),不如創建一個已找到的素數緩存並循環遍歷它們。 最快和最優雅的方法之一是使用functools.lru_cache ,但只需編寫自己的緩存就足夠了。

這是一種快速而骯臟的方法,比您的原始提議更長但更有效:

from math import sqrt

# We seed the cache with the first two odd primes because (1) it's low-
# hanging fruit and (2) we avoid the need to add extra lines of code (that
# will increase execution time) for cases in which the square roots of numbers
# are less than any primes in the list
odd_primes = [3, 5]

def is_prime(n):
    
    # If n is not prime, it must have at least one factor less than its square 
    # root.
    max_prime_factor_limit = int(sqrt(n))
    
    # use a generator here to avoid evaluating all the qualifying values in 
    # odd_primes until you need them. For example, the square root of 27 is
    # 5.1962, but, since it's divisible by 3, you'll only test if 27 is prime
    # one time. Not a big deal with smaller integers, but the time to compute
    # the next prime will increase pretty fast as there are more potential
    # factors.
    
    available_primes = (p for p in odd_primes if p <= max_prime_factor_limit)
    
    for prime in available_primes:
        if n % prime == 0:
            return False
    
    return True


for i in range(7, 99, 2):
    # if no prime factors were found, add to cache
    if is_prime(i):
        odd_primes.append(i)
        
print(odd_primes)

您可以做一些額外的事情來加快速度。 立即浮現在腦海的是,不是計算您要檢查的每個數字的平方根,而是使用素數的平方來確定您要檢查的素數集的上限。 換句話說,如果你知道 169 的平方是 13,那么你就知道任何大於 169 且小於 289(17 的平方)的數都有一個質因數 <= 13。你也可以用它來保存通過計算素數列表並將列表傳遞給 function 來確定 integer 是否為素數。 當然,請注意,這僅在您實際創建素數列表時才有效。

number = int(input('please enter a number:'))
if number>1:
    for numbers in range(2, number):
        if (number % numbers) ==0:
            print(f"{number} is not a prime number")
         
            break
    else:
        print(f"{number} is a prime number")  
else:
    print(f"{number} is not a prime number")

暫無
暫無

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

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