Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Pythagorean triplet for which a + b + c = 1000

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2

For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.

Source: http://projecteuler.net/index.php?section=problems&id=9

I tried but didn't know where my code went wrong. Here's my code in C:

#include <math.h> #include <stdio.h> #include <conio.h>   void main() {     int a=0, b=0, c=0;     int i;     for (a = 0; a<=1000; a++)     {         for (b = 0; b<=1000; b++)         {             for (c = 0; c<=1000; c++)             {                 if ((a^(2) + b^(2) == c^(2)) && ((a+b+c) ==1000)))                     printf("a=%d, b=%d, c=%d",a,b,c);             }         }     } getch();     } 
like image 874
Rahul Avatar asked May 12 '10 10:05

Rahul


People also ask

What is the Pythagorean triplet of 1000?

For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000.

How many Pythagorean triples are there under 1000?

Up to 1000: 325 triples, 70 primitives. Up to 10000: 4858 triples, 703 primitives. Up to 100000: 64741 triples, 7026 primitives. Up to 1000000: 808950 triples, 70229 primitives.

How do you find a Pythagorean triplet for Class 7?

Pythagorean triples are a2+b2 = c2 where a, b and c are the three positive integers. These triples are represented as (a,b,c). Here, a is the perpendicular, b is the base and c is the hypotenuse of the right-angled triangle. The most known and smallest triplets are (3,4,5).


2 Answers

#include <math.h> #include <stdio.h>  int main() {     const int sum = 1000;     int a;     for (a = 1; a <= sum/3; a++)     {         int b;         for (b = a + 1; b <= sum/2; b++)         {             int c = sum - a - b;             if ( a*a + b*b == c*c )                printf("a=%d, b=%d, c=%d\n",a,b,c);         }     }     return 0; } 

explanation:

  • b = a;
    if a, b (a <= b) and c are the Pythagorean triplet,
    then b, a (b >= a) and c - also the solution, so we can search only one case
  • c = 1000 - a - b; It's one of the conditions of the problem (we don't need to scan all possible 'c': just calculate it)
like image 71
Oleg Razgulyaev Avatar answered Oct 14 '22 05:10

Oleg Razgulyaev


I'm afraid ^ doesn't do what you think it does in C. Your best bet is to use a*a for integer squares.

like image 33
Paul Stephenson Avatar answered Oct 14 '22 05:10

Paul Stephenson