毕达哥拉斯三胞胎的总和是1000?

时间:2013-04-19 11:40:18

标签: c++ pythagorean

项目欧拉问题9.我试图解决它,事实上我得到的三胞胎不是毕达哥拉斯三胞胎,他们的总和是1000,为什么?我确定他们是毕达哥拉斯三胞胎。这是我漫长而不那么优化的代码:

#include <iostream>
#include <math.h>

using namespace std;

int main()
{
    int a,b,c; //Decalring the triplets...
    a=1; //First triplet starts with 3
    b=1;
    int c2;//c square

    while(true)
    {
        for(b=1;b<a;b++){
        c2 = a*a+b*b;
        c = sqrt(c2);
        if(c*c == c2 && a+b+c==1000)
        {
            cout<<a<<","<<b<<","<<c<<"\n";
        }
        a++;
        }
        b++;
    }
}

最终工作代码:

#include <iostream>
#include <math.h>

using namespace std;

int main()
{
    int x,y,z,a;
    for(x=1;x<=1000;x++)
    {
        for(y=1;y<=1000;y++)
        {
            a = x*x+y*y;
            z=sqrt(a);
            if(z*z==a && x+y+z==1000 && x<y){
            cout<<x<<","<<y<<","<<z<<"."<<"\n";
            cout<<"So the product of all of the three triplets is "<<x*y*z;
            }
        }
    }
    return 0;
}

3 个答案:

答案 0 :(得分:2)

您的循环条件已关闭。与当前ca对应的b在循环中计算。因此,您无法在c的值上测试循环迭代,因为它是旧的。从条件中移除c,将sqrt(c2)的完整性放回测试中,然后您就可以找到解决方案。

修改

您似乎试图通过执行或多或少的随机代码更改来获得结果。那是让你无处可去。

首先用简单的人类语言清楚地制定你的算法。然后将其重新命名为与C ++代码概念相匹配的(仍然简单的人类语言)结构。然后编写这些概念。

这样的事情:

步骤1.在毕达哥拉斯三元组中,第三个成员c完全由前两个成员决定。因此,我将检查ab的所有可能值,如果它们形成毕达哥拉斯三元组,则测试它的总和为1000。

步骤2.对于每个a,我将测试大于b的所有a,使a + b小于1000.我将计算{{1}并看看它是否是正方形。如果是这样,我将测试三元组的总和。

第3步。

c2

答案 1 :(得分:1)

您应该检查以确保c2实际上是正方形。一种方法是在取平方根后检查c*c == c2是否正确。

答案 2 :(得分:1)

//My brute force solution works fine
since i<j<k
start j loop from i+1 and k loop from j+1
whenever the condition satisfies print the product of triplet

#include<iostream>
using namespace std;
int main()
{
    for(long long i=1;i<=1000;i++)
    {
        for(long long j=i+1;j<=1000;j++)
        {
            for(long long k=j+1;k<=1000;k++)
            {
                if((i+j+k)==1000 && i*i+j*j==k*k)
                {
                cout<<i*j*k<<endl;
                }
            }
        }
    }
}