Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
979 views
in Technique[技术] by (71.8m points)

c++ - Different results on using sqrt() and pow() functions

I was solving Euler problem no. 10 that asks to find sum of all primes below 2million. I am getting different results on using sqrt and pow functions. Using sqrt gives the correct answer, plus using pow function takes more time. Here is my code.

for(sum=0,i=3;i<=2000000;i+=2)
{
    for(j=3;j<=sqrt(i);j++)
        if(i%j==0)
            break;
    if(j>sqrt(i))
        sum+=i;
}
sum+=2;
std::cout << "
Sum = " << sum;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I can not reproduce your problem on my computer, but your testing on double is a very dangerous one. If i is the square of a prime number you are relying on high precision of the sqrt and pow to have the correct result. Maybe on your system there is a slight rounding difference on one or more of such squares. You'd better test j*j <= i and j*j > i.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...