[英]Number of primes less than or equal to x
Below code gives number of primes less than or equal to N下面的代码给出了小于或等于 N 的素数
It works perfect for N<=100000,它适用于 N<=100000,
Input - Output Table输入 - 输出表
| Input | Output | |-------------|---------------| | 10 | 4✔ | | 100 | 25✔ | | 1000 | 168✔ | | 10000 | 1229✔ | | 100000 | 9592✔ | | 1000000 | 78521✘ |
However, π(1000000) = 78498然而,π(1000000) = 78498
import time def pi(x): nums = set(range(3,x+1,2)) nums.add(2) #print(nums) prm_lst = set([]) while nums: p = nums.pop() prm_lst.add(p) nums.difference_update(set(range(p, x+1, p))) #print(prm_lst) return prm_lst if __name__ == "__main__": N = int(input()) start = time.time() print(len(pi(N))) end= time.time() print(end-start)
You can read from this thread the fastest way like below and with this function for n = 1000000
I find correctly 78498
prime numbers.您可以像下面这样以最快的方式从该线程中读取数据,并使用此函数在n = 1000000
正确找到78498
素数。 (I change one line in this function) (我在此功能中更改了一行)
From:从:
return ([2] + [i for i in range(3,n,2) if sieve[i]])
To:到:
return len([2] + [i for i in range(3,n,2) if sieve[i]])
Finally:最后:
def primes(n):
sieve = [True] * n
for i in range(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)
return len([2] + [i for i in range(3,n,2) if sieve[i]])
inp = [10, 100, 1000, 10000, 100000, 1000000]
for i in inp:
print(f'{i}:{primes(i)}')
Output:输出:
10:4
100:25
1000:168
10000:1229
100000:9592
1000000:78498
You code is only correct if nums.pop()
returns a prime, and that in turn will only be correct if nums.pop()
returns the smallest element of the set.只有当nums.pop()
返回素数时,您的代码才是正确的,而只有当nums.pop()
返回集合中的最小元素时,代码才是正确的。 As far as I know this is not guaranteed to be true.据我所知,这不能保证是真的。 There is a third-party module called sortedcontainers that provides a SortedSet class that can be used to make your code work with very little change.有一个名为sortedcontainers的第三方模块,它提供了一个 SortedSet 类,可用于使您的代码只需很少的更改即可工作。
import time
import sortedcontainers
from operator import neg
def pi(x):
nums = sortedcontainers.SortedSet(range(3, x + 1, 2), neg)
nums.add(2)
# print(nums)
prm_lst = set([])
while nums:
p = nums.pop()
prm_lst.add(p)
nums.difference_update(set(range(p, x + 1, p)))
# print(prm_lst)
return prm_lst
if __name__ == "__main__":
N = int(input())
start = time.time()
print(len(pi(N)))
end = time.time()
print(end - start)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.