【发布时间】:2015-04-04 05:40:22
【问题描述】:
我正在尝试优化我的代码以在 hadoop 集群上运行。谁能帮我找到一些方法来改善它?我正在接受一组非常大的数字 40+ 百万,每个数字都在一个新的行上。在读入数字时,我正在计算每个数字,将所有数字相加,并检查每个数字是否为素数。
#!/usr/bin/env python
import sys
import string
import math
total_of_primes = 0
total = 0
count = 0
not_prime = 0
count_string = 'Count:'
total_string = 'Total:'
prime_string = 'Number of Primes:'
for line in sys.stdin:
try:
key = int(line)
except:
continue
total = total + key
count = count + 1
if key == 2 or key == 3:
not_prime = not_prime - 1
elif key%2 == 0 or key%3 == 0:
not_prime = not_prime + 1
else:
for i in range(5,(int(math.sqrt(key))+1),6):
if key%i == 0 or key%(i+2) ==0:
not_prime = not_prime + 1
break
total_of_primes = count - not_prime
print '%s\t%s' % (count_string,count)
print '%s\t%s' % (total_string,total)
print '%s\t%s' % (prime_string,total_of_primes)
【问题讨论】:
-
当你看到 2 或 3 时,为什么要减少合数的计数?
-
2 和 3 都是质数,但 1 不是。
-
是的,但如果输入只是两个数字 2 和 3,你见过负的两个合数吗?
-
没错,我改了。创建了一个跟踪素数的变量,如果读入 2 和 3,只需添加到该变量。
-
可以读取的最大数字是多少?
标签: python hadoop optimization mapreduce primes