使用SQRT()和POW不同的结果()函数 [英] Different results on using sqrt() and pow() functions

查看:1267
本文介绍了使用SQRT()和POW不同的结果()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是解决问题的欧拉没有。 10,要求寻找200万以下的所有素数的总和。
我使用开方 POW 功能得到不同的结果。
使用开方给出了正确的答案,再加上使用POW功能需要更多的时间。这里是我的code。

 为(总和= 0,I = 3; I< = 2000000;我+ = 2)
{
    为(J = 3; J&下; = SQRT(ⅰ); J ++)
        如果(我引用%j == 0)
            打破;
    如果(J>的sqrt(I))
        总和+ =我;
}
总和+ = 2;
性病::法院LT&;< \\ nSum =<<和;


解决方案

首先,的sqrt(x)的的更快,更比准确POW(X,0.5),为什么你认为这是在图书馆?其次,你可能会得到一个错误的答案,因为你的循环终止条件测试浮点数。一个微小的四舍五入在那些200万环路的一个地方大概是足以甩开总。最后,你计算浮点开方()两次循环,这是非常缓慢的每次迭代里面。

而不是

 为(J = 0; J< =开方(I)+ J) 。 。

尝试

 极限=(INT)(开方(我)+ 0.5);
为(J = 0; J< =限制; ++ j)条。 。 。

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 << "\nSum = " << sum;

解决方案

First of all, sqrt(x) should be faster and more accurate than pow(x,0.5), why do you think it's in the library? Second, you're probably getting a wrong answer because your loop termination condition is testing a floating-point number. A tiny round-off somewhere in one of those 2 million loops is probably enough to throw off the total. Finally, you're calculating a floating point sqrt() twice inside each iteration of the loop, which is terribly slow.

Instead of

for (j = 0; j <= sqrt(i); ++j)  . . .

try

limit = (int)(sqrt(i) + 0.5);
for (j = 0; j <= limit; ++j) . . .

这篇关于使用SQRT()和POW不同的结果()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆