簡體   English   中英

如何在 python 中找到素數

[英]How to find prime numbers in python

我是 Python 的新手。 我正在嘗試計算給定范圍內的素數。 開發者分享的一些答案是這樣的:

import math
def count_primes(num):
    out = []

    for i in range(3,num,2):
        if all(i%j!=0 for j in range(3,int(math.sqrt(i))+1,2)):
            out.append(i)

    print(out)

我寫了一個這樣的:

import math
def count_primes(num):
    out = []
    for i in range(3,num,2):
        for j in range(3, int(math.sqrt(i))+1,2):
            if i%j != 0:
                out.append(i)           
        print(out)

但它不起作用。 有人可以幫助我嗎? 贊賞!

您的示例count_primes()函數實際上都沒有計算素數——它們只是打印奇數素數。 讓我們實現一個試用版代碼的工作版本,不要使用令人困惑的布爾值和糟糕的算法,而是利用 Python 在for循環中的else子句:

def collect_odd_primes(number):
    primes = []

    for candidate in range(3, number, 2):
        for divisor in range(3, int(candidate ** 0.5) + 1, 2):
            if candidate % divisor == 0:
                break
        else:  # no break
            primes.append(candidate)

    return primes

print(collect_odd_primes(40))

OUTPUT

> python3 test.py
[3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
>

正如@MarkRansom 評論的那樣, Eratosthenes 的篩子是 go 的更好方法。 (+1) 現在,讓我們將代碼轉換為計算奇數素數:

def count_odd_primes(number):
    count = 0

    for candidate in range(3, number, 2):
        for divisor in range(3, int(candidate ** 0.5) + 1, 2):
            if candidate % divisor == 0:
                break
        else:  # no break
            count += 1

    return count

print(count_odd_primes(40))

OUTPUT

> python3 test.py
11
> 

像這樣的東西應該工作。 您必須設置一個變量,因為15%9 != 0輸出 True。

import math
def count_primes(num):
    out = []
    for i in range(3,num,2):
        prime = True
        for j in range(3, int(math.sqrt(i))+1,2):
            if i%j == 0:
                prime = False
        if prime:
            out.append(i)
    print(out)
    
count_primes(15)

您的代碼和另一個代碼不同的原因是它們使用了all()方法。 看看我是如何使用bool s 實現該方法的:

import math
def count_primes(num):
    out = []
    for i in range(3,num,2):
        f = True
        for j in range(3,int(math.sqrt(i))+1,2):
            if i%j==0:
                f = False
                break
        if f:
            out.append(i)

    print(out)
    
count_primes(20)

Output:

[3, 5, 7, 11, 13, 17, 19]

您附加到模塊的結果不等於零。 但是,如果所有模都不等於零,它只是一個素數(代碼中缺少 all 語句)。

根據您為編寫代碼而運行的程序,另一種方法(與此問題的其他答案相反)將是:

    n = int(input("Write an integer:"))
    m = 2

    if n == 1:
        print(n, "is a prime number!")

    if n == 2:
        print(n, "is not a prime number.")

    while n > m:
        if n % m == 0:
            m = m + 1
            print(n, "is not a prime number.")
            break

        if n > n % m > 0:
            m = m + 1
            print(n, "is a prime number!")
            break

它可能不是最有效的,但它為您提供了一個非常好的、直接的答案來判斷“x”是否是質數!

暫無
暫無

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

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