所以,我正在解决问题10,并达成一个解决方案:
acu = 0;
for(i=2;i<=2000000;i++){
if(primo(i)== 1){
acu = acu + i;
}
}
primo是:
int primo(long num){
long pd;
pd = num/2;
while(pd > 1 && num%pd != 0){
pd--;
}
if (pd == 1)
return 1;
else
return -1;}
在我的机器上执行的时间大约是700秒。然后我在代码中更改了这个:
int primo(long num){
long pd;
pd = lround(sqrt(num));
while(pd > 1 && num%pd != 0){
pd--;
}
if (pd == 1)
return 1;
else
return -1;}
并且执行的时间是15秒。为什么num / 2和lround(sqrt(num))之间有这么大差异?
答案 0 :(得分:1)
简单地说,在更糟糕的情况下(当num
为素数时),第一个实现将循环num/2
次,但第二个将循环sqrt(num)
次,当然sqrt(num)
远低于num/2
,因此第二次实施所需的时间低于第一次实施所需的时间。
编辑:
如果你想要比你使用的两个实现更快的另一个实现,那就是:
int primo(long num){
if(num==2) return 1; //2 is even but prime so we check it herer cause the next test will return 0 for even bumbers
if(num%2==0) return 0; //if it is a multiple of 2 it is not a prime number so we do not loop in this case
long nb_sqrt= lround(sqrt(num));
if(nb_sqrt%2==0) nb_sqrt++; //start from an odd number (explained in the loop)
while(num%nb_sqrt != 0) nb_sqrt-=2; //decrements by 2 since the number is not a multiple of 2 (already checkef) so it will not be divided by an even number
return nb_sqrt==1;
}
答案 1 :(得分:0)
因为while
循环的迭代次数不同:
num = 2000000
# Number of iterations in case 1
num/2 => 1000000
# Number of iterations in case 2
lround( sqrt(2000000)) = 1414
此外,在for循环中重复调用primo
。