Question:codility Lesson11 CountSemiprimes
My Answer:
from math import sqrt
def solution(N,P,Q):
sieve = [True] * (N + 1)
sieve[0] = False
sieve[1] = False
prime = []
i = 2
while i * i <= N:
if sieve[i] == True:
k = i * i
prime.append(i)
while (k <= N):
sieve[k] = False
k += i
i += 1
for ele in range(i,N + 1):
if sieve[ele] == True:
prime.append(ele)
primecnt = len(prime)
semiprimes = [0] * (N + 1)
for i in range(primecnt - 1):
for j in range(i,primecnt):
if prime[i] * prime[j] > N:
break
semiprimes[prime[i] * prime[j]] = 1
for i in range(1,N + 1):
semiprimes[i] += semiprimes[i - 1]
res = []
for i in range(len(P)):
res.append(semiprimes[Q[i]] - semiprimes[P[i] - 1])
return res

本文介绍了一个用于解决 Codility Lesson 11 CountSemiprimes 问题的有效算法。通过使用筛法求得所有质数,并进一步找出半质数(即两个质数的乘积),该算法能够在 O(N log log N + M) 的时间内处理多个查询区间内的半质数计数。
341

被折叠的 条评论
为什么被折叠?



