1

Project Euler problem 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;
}
4

3 に答える 3

2

ループ条件がオフです。はc電流に対応しa、ループbで計算されます。したがって、古い値であるため、 の値でループ反復をテストすることはできません。条件から外し、 の完全性のテストを元に戻すと、解が得られます。ccsqrt(c2)

編集

多かれ少なかれランダムなコード変更を行って結果を得ようとしているようです。それはあなたをどこにも連れて行きません

アルゴリズムを平易な人間の言葉で明確に定式化することから始めます。次に、それを C++ コードの概念に一致する (まだ平易な人間の言語) 構造に言い換えます。次に、それらの概念をコーディングします。

このようなもの:

ステップ 1. ピタゴラスのトリプレットでは、3 番目の要素cは最初の 2 要素によって完全に決定されます。そこで、 と のすべての可能な値を調べてabそれらがピタゴラスのトリプレットを形成する場合、合計が 1000 であるかテストします。

ステップ 2. 各 について、 1000 未満の よりも大きいすべての s をテストします。計算してa、それが正方形かどうかを確認します。もしそうなら、私はトリプレットの合計をテストします。baa + 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
//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 に答える