我想优化我的代码以在hadoop集群上运行。任何人都可以帮助我找到一些方法来改善这一点吗?我正在接受一组数量超过四千万的数字,每个数字都在一个新的线上。随着数字读入我计算每个数字,总结所有数字,并检查每个数字,看看它是否是一个素数。需要更快的地图功能
#!/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时减少*合计数? – user2357112 2015-04-04 05:57:39
2和3都是素数,但1不是。 – 2015-04-04 06:29:29
是的,但如果输入只是两个数字2和3,你看到负两个复合数字吗? – user2357112 2015-04-04 06:45:13