본문 바로가기
Programming/Project Euler

9, Project Euler #9 : Special Pythagorean triplet

by 작은별하나 2015. 4. 20.

Difficulty rating is 5%.



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.


This problem is Pythagorean triplet with length is 1,000.

Pythagorean triplet generation method is well known.  We can get primitive Pythagorean with this method.


For gcd(t, s) = 1 and t+s is odd number.



We can get Pythagorean triplets multiplying some number to primitive Pythagorean triplet.


This is my code.


#include <stdio.h>

int main()
{
    int s, t;
    int n = 1000;

    for( s = 2 ; s*s < n/2 ; s++ )
    {
        for( t = 1 ; t < s ; t++ )
        {
            int x = 2*t*s;
            int y = s*s - t*t;
            int z = s*s + t*t;

            if( x + y + z == n )
            {
                printf("%d^2 + %d^2 = %d^2\n", x, y, z);
                printf("Ans = %d\n", x*y*z);
            }
        }
    }
}


댓글