use*_*096 3 python performance primes
您好,有人能告诉我如何在此代码中实现Eratosthenes筛选以使其快速?如果你能用筛子完成它,将非常感谢帮助.在这个特定的代码中,我真的遇到了麻烦.
#!/usr/bin/env python
import sys
T=10 #no of test cases
t=open(sys.argv[1],'r').readlines()
import math
def is_prime(n):
if n == 2:
return True
if n%2 == 0 or n <= 1:
return False
sqr = int(math.sqrt(n)) + 1
for divisor in range(3, sqr, 2):
if n%divisor == 0:
return False
return True
#first line of each test case
a=[1,4,7,10,13,16,19,22,25,28]
count=0
for i in a:
b=t[i].split(" ")
c=b[1].split("\n")[0]
b=b[0]
for k in xrange(int(b)):
d=t[i+1].split(" ")
e=t[i+2].split(" ")
for g in d:
for j in e:
try:
sum=int(g)+int(j)
p=is_prime(sum)
if p==True:
count+=1
print count
else:
pass
except:
try:
g=g.strip("\n")
sum=int(g)+int(j)
p=is_prime(sum)
if p==True:
count+=1
print count
else:
pass
except:
j=j.strip("\n")
sum=int(g)+int(j)
p=is_prime(sum)
if p==True:
count+=1
print count
else:
pass
print "Final count"+count
Run Code Online (Sandbox Code Playgroud)
Tim*_*ers 12
在Python中加速筛分的一个老技巧是使用花式;-) list slice表示法,如下所示.这使用Python 3.注释中注明了Python 2所需的更改:
def sieve(n):
"Return all primes <= n."
np1 = n + 1
s = list(range(np1)) # leave off `list()` in Python 2
s[1] = 0
sqrtn = int(round(n**0.5))
for i in range(2, sqrtn + 1): # use `xrange()` in Python 2
if s[i]:
# next line: use `xrange()` in Python 2
s[i*i: np1: i] = [0] * len(range(i*i, np1, i))
return filter(None, s)
Run Code Online (Sandbox Code Playgroud)
在Python 2中,它返回一个列表; 在Python 3中是一个迭代器.这里是Python 3:
>>> list(sieve(20))
[2, 3, 5, 7, 11, 13, 17, 19]
>>> len(list(sieve(1000000)))
78498
Run Code Online (Sandbox Code Playgroud)
这两个都在眨眼间.鉴于此,这是如何构建一个is_prime函数:
primes = set(sieve(the_max_integer_you_care_about))
def is_prime(n):
return n in primes
Run Code Online (Sandbox Code Playgroud)
set()这是让它变得快速的部分.当然功能很简单你可能想写:
if n in primes:
Run Code Online (Sandbox Code Playgroud)
直接而不是搞乱:
if is_prime(n):
Run Code Online (Sandbox Code Playgroud)
原始海报和此处发布的其他解决方案都犯了同样的错误; 如果您使用模运算符或任何形式的除法,您的算法是试验分区,而不是 Eratosthenes的Sieve,并且将慢得多,O(n ^ 2)而不是O(n log log n).这是Python中一个简单的Eratosthenes Sieve:
def primes(n): # sieve of eratosthenes
ps, sieve = [], [True] * (n + 1)
for p in range(2, n + 1):
if sieve[p]:
ps.append(p)
for i in range(p * p, n + 1, p):
sieve[i] = False
return ps
Run Code Online (Sandbox Code Playgroud)
这应该会在不到一秒的时间内找到所有不到一百万的素数.如果你对使用素数编程感兴趣,我谦虚地在我的博客上推荐这篇文章.
| 归档时间: |
|
| 查看次数: |
14164 次 |
| 最近记录: |