python求素数算法
There are various methods through which we can calculate prime numbers upto n.
我们可以通过多种方法来计算最大为n的素数 。
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).
在这种方法中,我们通常运行两个for循环,其中第一个循环用于增加数字,第二个循环用于检查数字是否为质数。 第二个循环从2到(n / 2 +1)运行(以获得更好的性能)。
Note: This is the least efficient method (one should not use this if efficiency is required.)
注意:这是效率最低的方法(如果需要效率,则不应使用此方法。)
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.
在此方法中,运行两个循环,第一个循环是增加数字,第二个循环是检查数字是否为质数。 第二个循环从2到平方根(数字)(要检查的数字),这就是为什么第二个for循环的运行长度相对较小的原因,这就是为什么它比幼稚的方法有效的原因。
3) Sieve of Eratosthenes
3)Eratosthenes筛
This is the best and most efficient method to calculate the prime numbers upto n.
这是计算最高达n的素数的最佳和最有效的方法。
Algorithm for Sieve of Eratosthenes:
Eratosthenes筛分算法:
Let A be an array from 2 to n.
设A为2到n的数组。
Set all the values to
将所有值设置为
True (we are considering every number to be Prime)
正确 (我们认为每个数字都是素数)
For loop from p == 2 (smallest prime number)
从p == 2开始的循环(最小质数)
For loop from p2 to n
从p 2到n的循环
Mark all the multiples of
标记所有的倍数
p as False and increase the value of p to the next prime number
数p作为假和增加p值到下一个素数
End of second FOR loop
第二个FOR循环结束
End of first FOR loop
第一个FOR循环结束
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.
在两个for循环的末尾,在步骤3中,所有标记为TRUE的值均为质数,所有复合数字均标记为FALSE。
Time complexity : O(n*log(log(n)))
时间复杂度: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数,则通用方法和SquareRoot方法的性能可以提高一点,因为不是2的偶数不是素数。
Example:
例:
from time import time
from math import sqrt
def general_approach(n):
'''
Generates all the prime numbers from 2 to n - 1.
n - 1 is the largest potential prime considered.
'''
start = time()
count = 0
for i in range(2, n):
flag = 0
x = i // 2 + 1
for j in range(2, x):
if i % j == 0:
flag = 1
break
if flag == 0:
count += 1
stop = 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 = 0
for val in range(2, n):
root = round(sqrt(val)) + 1
for trial_factor in range(2, root):
if val % trial_factor == 0:
break
else:
count += 1
stop = 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 otherwise
nonprimes = n * [False]
count = 0
nonprimes[0] = nonprimes[1] = True
for i in range(2, n):
if not nonprimes[i]:
count += 1
for j in range(2*i, n, i):
nonprimes[j] = True
stop = 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 == 200000
Sieve of Eratosthenes Method
Count = 17984 Elapsed time: 0.050385475158691406 seconds
Square Root Method
Count = 17984 Elapsed time: 0.9392056465148926 seconds
General Approach
Count = 17984 Elapsed time: 101.83296346664429 seconds
翻译自: https://www.includehelp.com/python/calculate-prime-numbers-using-different-algorithms-upto-n-terms.aspx
python求素数算法