c++ - Pythagorean triplets whose sum is 1000? -
project euler problem 9. tried solve it, infact triplets not pythagorean triplets , sum 1000, why? made sure pythagorean triplets. here long , not optimized code:
#include <iostream> #include <math.h> using namespace std; int main() { int a,b,c; //decalring triplets... a=1; //first triplet starts 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++) { = x*x+y*y; z=sqrt(a); if(z*z==a && x+y+z==1000 && x<y){ cout<<x<<","<<y<<","<<z<<"."<<"\n"; cout<<"so product of of 3 triplets "<<x*y*z; } } } return 0; }
your loop conditions off. c corresponding current a , b computed inside loop. therefore, cannot test loop iteration on value of c because it's old one. remove c conditions, put test integrality of sqrt(c2), , have solution.
edit
you seem trying results doing more or less random code changes. not going ot anywhere.
start formulating algorithm in plain human language. re-word (still plain human language) structure matching c++ code concepts. code concepts.
something this:
step 1. in pythagorean triplet, third member c determined first two. examine possible values of a , b, , if form pythagorean triplet, test sum of 1000.
step 2. each a, test bs larger a such a + b less 1000. compute c2 , see if it's square. if so, test sum of triplet.
step 3.
#include <cmath> #include <iostream> int main() { (int = 3; < 1000; ++a) { (int b = + 1; + b < 1000; ++b) { int c2 = * + b * b; int c = std::sqrt(c2); if (c * c == c2) { if (a + b + c == 1000) { std::cout << "found triplet " << << ", " << b << ", " << c << '\n'; } } } } }
Comments
Post a Comment