1

Project Euler problem 9. I tried to solve it, infact I get triplets which are not Pythagorean triplets and their sum is 1000, Why? I made sure they were Pythagorean triplets. Here is my long and not so optimized code:

#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++;
    }
}

Final working code:

#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;
}
4

3 回答 3

2

您的循环条件已关闭。c对应于当前的和a在循环b计算。因此,您不能测试循环迭代的值,因为它是旧的。从条件中删除,重新测试 的完整性,您就有了解决方案。ccsqrt(c2)

编辑

您似乎试图通过或多或少的随机代码更改来获得结果。那不会让你到任何地方。

首先用简单的人类语言清楚地制定你的算法。然后将其改写为匹配 C++ 代码概念的(仍然是简单的人类语言)结构。然后对这些概念进行编码。

像这样的东西:

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

第 2 步。对于每个a,我将测试所有大于b小于1000 的 s。我将计算并查看它是否是正方形。如果是这样,我将测试三元组的总和。aa + bc2

步骤 3。

#include <cmath>
#include <iostream>

int main()
{
  for (int a = 3; a < 1000; ++a) {
    for (int b = a + 1; a + b < 1000; ++b) {
      int c2 = a * a + b * b;
      int c = std::sqrt(c2);
      if (c * c == c2) {
        if (a + b + c == 1000) {
          std::cout << "Found triplet " << a << ", " << b << ", " << c << '\n';
        }
      }
    }
  }
}
于 2013-04-19T12:04:54.500 回答
1

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

于 2013-04-19T11:43:47.100 回答
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;
                }
            }
        }
    }
}
于 2015-06-02T15:55:49.943 回答