Python3 程序计算范围内的素数
给定一个范围 [L, R],我们需要找到范围 [L, R] 中素数总数的计数,其中 0 <= L <= R < 10000。考虑到有大量查询不同的范围。
例子:
Input : Query 1 : L = 1, R = 10
Query 2 : L = 5, R = 10
Output : 4
2
Explanation
Primes in the range L = 1 to R = 10 are
{2, 3, 5, 7}. Therefore for query, answer
is 4 {2, 3, 5, 7}.
For the second query, answer is 2 {5, 7}.
一个简单的解决方案是对每个查询 [L, R] 执行以下操作。从 L 遍历到 R,检查当前数字是否为素数。如果是,则增加计数。最后,返回计数。
一个有效的解决方案是使用埃拉托色尼筛法找出所有达到给定极限的素数。然后我们计算一个前缀数组来存储计数,直到限制之前的每个值。一旦我们有了前缀数组,我们就可以在 O(1) 时间内回答查询。我们只需要返回前缀[R] – 前缀[L-1]。
Python3
# Python3 program to answer queries for
# count of primes in given range.
MAX = 10000
# prefix[i] is going to
# store count of primes
# till i (including i).
prefix =[0]*(MAX + 1)
def buildPrefix():
# Create a boolean array value in
# prime[i] will "prime[0..n]". A
# finally be false if i is Not a
# prime, else true.
prime = [1]*(MAX + 1)
p = 2
while(p * p <= MAX):
# If prime[p] is not changed,
# then it is a prime
if (prime[p] == 1):
# Update all multiples of p
i = p * 2
while(i <= MAX):
prime[i] = 0
i += p
p+=1
# Build prefix array
# prefix[0] = prefix[1] = 0;
for p in range(2,MAX+1):
prefix[p] = prefix[p - 1]
if (prime[p]==1):
prefix[p]+=1
# Returns count of primes
# in range from L to
# R (both inclusive).
def query(L, R):
return prefix[R]-prefix[L - 1]
# Driver code
if __name__=='__main__':
buildPrefix()
L = 5
R = 10
print(query(L, R))
L = 1
R = 10
print(query(L, R))
# This code is contributed by mits.
输出:
2
4
有关详细信息,请参阅有关 Count Primes in Ranges 的完整文章!