python求素数算法_Python程序最多可计算n个质数(使用不同算法)
python求素?cái)?shù)算法
There are various methods through which we can calculate prime numbers upto n.
我們可以通過(guò)多種方法來(lái)計(jì)算最大為n的素?cái)?shù) 。
1) General Method
1)一般方法
In this method, we usually run two for loops in which the First one is used to increase the number and the second one is used to check whether the number is prime or not. Second loop runs from 2 to ( n / 2 + 1 ) ( for better performance).
在這種方法中,我們通常運(yùn)行兩個(gè)for循環(huán),其中第一個(gè)循環(huán)用于增加數(shù)字,第二個(gè)循環(huán)用于檢查數(shù)字是否為質(zhì)數(shù)。 第二個(gè)循環(huán)從2到(n / 2 +1)運(yùn)行(以獲得更好的性能)。
Note: This is the least efficient method (one should not use this if efficiency is required.)
注意:這是效率最低的方法(如果需要效率,則不應(yīng)使用此方法。)
2) Square-Root Method
2)平方根法
In this method, two loops run first one is to increase the number and the second one is to check whether the number is prime or not. The second loop runs from 2 to square root (number) (a number which is to be check), that’s why the run length of second for loop is relatively small, that’s why it’s efficient than the na?ve approach.
在此方法中,運(yùn)行兩個(gè)循環(huán),第一個(gè)循環(huán)是增加數(shù)字,第二個(gè)循環(huán)是檢查數(shù)字是否為質(zhì)數(shù)。 第二個(gè)循環(huán)從2到平方根(數(shù)字)(要檢查的數(shù)字),這就是為什么第二個(gè)for循環(huán)的運(yùn)行長(zhǎng)度相對(duì)較小的原因,這就是為什么它比幼稚的方法有效的原因。
3) Sieve of Eratosthenes
3)Eratosthenes篩
This is the best and most efficient method to calculate the prime numbers upto n.
這是計(jì)算最高達(dá)n的素?cái)?shù)的最佳和最有效的方法。
Algorithm for Sieve of Eratosthenes:
Eratosthenes篩分算法:
Let A be an array from 2 to n.
設(shè)A為2到n的數(shù)組。
Set all the values to
將所有值設(shè)置為
True (we are considering every number to be Prime)
正確 (我們認(rèn)為每個(gè)數(shù)字都是素?cái)?shù))
For loop from p == 2 (smallest prime number)
從p == 2開(kāi)始的循環(huán)(最小質(zhì)數(shù))
For loop from p2 to n
從p 2到n的循環(huán)
Mark all the multiples of
標(biāo)記所有的倍數(shù)
p as False and increase the value of p to the next prime number
數(shù)p作為假和增加p值到下一個(gè)素?cái)?shù)
End of second FOR loop
第二個(gè)FOR循環(huán)結(jié)束
End of first FOR loop
第一個(gè)FOR循環(huán)結(jié)束
At the end of both the for loops, all the values that are marked as TRUE are primes and all the composite numbers are marked as FALSE in step 3.
在兩個(gè)for循環(huán)的末尾,在步驟3中,所有標(biāo)記為T(mén)RUE的值均為質(zhì)數(shù),所有復(fù)合數(shù)字均標(biāo)記為FALSE。
Time complexity : O(n*log(log(n)))
時(shí)間復(fù)雜度:O(n * log(log(n)))
Note: Performance of General Method and SquareRoot Method can be increased a little bit if we check only ODD numbers because instead of 2 no even number is prime.
注意:如果只檢查ODD數(shù),則通用方法和SquareRoot方法的性能可以提高一點(diǎn),因?yàn)椴皇?的偶數(shù)不是素?cái)?shù)。
Example:
例:
from time import time from math import sqrtdef general_approach(n):'''Generates all the prime numbers from 2 to n - 1.n - 1 is the largest potential prime considered.'''start = time()count = 0for i in range(2, n):flag = 0x = i // 2 + 1for j in range(2, x):if i % j == 0:flag = 1breakif flag == 0:count += 1stop = time()print("Count =", count, "Elapsed time:", stop - start, "seconds")def count_primes_by_sqrt_method(n):'''Generates all the prime numbers from 2 to n - 1.n - 1 is the largest potential prime considered.'''start = time()count = 0for val in range(2, n):root = round(sqrt(val)) + 1for trial_factor in range(2, root):if val % trial_factor == 0:breakelse:count += 1stop = time()print("Count =", count, "Elapsed time:", stop - start, "seconds")def seive(n):'''Generates all the prime numbers from 2 to n - 1.n - 1 is the largest potential prime considered.Algorithm originally developed by Eratosthenes.'''start = time()# Each position in the Boolean list indicates# if the number of that position is not prime:# false means "prime," and true means "composite."# Initially all numbers are prime until proven otherwisenonprimes = n * [False]count = 0nonprimes[0] = nonprimes[1] = Truefor i in range(2, n):if not nonprimes[i]:count += 1for j in range(2*i, n, i):nonprimes[j] = Truestop = time()print("Count =", count, "Elapsed time:", stop - start, "seconds")# Time complexity : O(n*log(log(n)))def main():print("For N == 200000\n")print('Sieve of Eratosthenes Method')seive(200000)print('\nSquare Root Method')count_primes_by_sqrt_method(200000)print('\nGeneral Approach')general_approach(200000)main()Output
輸出量
For N == 200000Sieve of Eratosthenes Method Count = 17984 Elapsed time: 0.050385475158691406 secondsSquare Root Method Count = 17984 Elapsed time: 0.9392056465148926 secondsGeneral Approach Count = 17984 Elapsed time: 101.83296346664429 seconds翻譯自: https://www.includehelp.com/python/calculate-prime-numbers-using-different-algorithms-upto-n-terms.aspx
python求素?cái)?shù)算法
總結(jié)
以上是生活随笔為你收集整理的python求素数算法_Python程序最多可计算n个质数(使用不同算法)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 2分值多少钱啊?
- 下一篇: 摩尔庄园高级鱼饵怎么获得