代码: 全选
# coding=utf-8
''' The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million. '''
import math
import time
'''分解因数,如果是素数返回'''
def factor(x, min = 2):
temp = min
while temp <= int(math.sqrt(x)) + 1: #从最小值到上界开始尝试
if x % temp == 0: return temp # 如果 a 能分解则返回最小因子
else: temp += 1
return 1 # 如果 a 是素数就返回 1,此处也可以设置为返回 x 本身
total = 0 # 总和
a = time.time() # 时间测试
for i in range(3, 200000): # 从 3 到 2000000 循环检测是否为素数
if factor(i) == 1: total += i # 若是则加入总和
b = time.time()
total += 2 # 补上 2
print total # 输出
print b - a # 输出时间
代码: 全选
/** The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million. */
#include "0.hpp"
#include <sys/timeb.h>
uu factor(uu a, uu min = 1)
{
uu temp = min;
uu sqr = (int)(sqrt((double)a) + _eps);
while(temp < sqr) if(a % ++temp == 0) break;
if(a % temp == 0) return temp;
else return 1;
}
int main()
{
const uu _max = 200000;
uu sum = 0;
timeb start, end;
ftime(&start);
for(uu i = 3; i <= _max; i += 2) {
if(factor(i) == 1) {
//cout << i << "\t";
sum += i;
}
}
sum += 2;
ftime(&end);
cout << sum << endl;
cout << (end.time - start.time) * 1000 + end.millitm - start.millitm << endl;
return 0;
}
谁能解释一下原因啊
小生这里拜谢了