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

#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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)