Docs


Problem 9: Special Pythagorean triplet

Problem

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.

Solution

/*
 * Special Pythagorean triplet
 * Problem 9 <https://projecteuler.net/problem=9>
 *
 * Project Euler
 *
 * By Ankit R Gadiya
 */

#include <stdio.h>

int sqr (int num);
int pythagorian_triplets (int num);

int main (void)
{
	int answer = pythagorian_triplets (1000);

	printf("Result: %i\n", answer);
	return 0;
}

int pythagorian_triplets (int num)
{
	int a, b, c, x, y;

	x = 2;
	do {
		y = 1;
		while (y < x) {
			a = sqr(x) - sqr(y);
			b = 2 * x * y;
			c = sqr(x) + sqr(y);

			if (a + b + c == num) {

				return a * b * c;
			}

			y++;
		}

		x++;
	} while (c < num);

	return -1;
}

int sqr (int num)
{
	return (num * num);
}

prob9.c

Result

31875000