Project Euler #9: Special Pythagorean Triplet

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.

The two solutions this program returns are {0,  500,  500} and {200, 375, 425}. I am unsure if the former is actually a pythagorean triplet, however, the second solution is correct.

#include <iostream>
#include <math.h>
bool createTriple(int a, int b);

int main(void)
{
	// Iterate up to 1000, arbitrary number
	for(int i = 0; i < 1000; i++)
	{	
		// Start at i to eliminate redunancies
		for(int j = i; j < 1000; j++)
		{
			// If the function returns true, triplet meeting criterion has been found
			if(createTriple(i, j))
			{
				// Output the found triplet
				std::cout << i << " " << j << " " << sqrt(pow(i, 2) + pow(j, 2)) << std::endl;
			}
		}
	}
	return 1;
}


bool createTriple(int a, int b)
{
	// Set c equal to a^2 + b^2
	int c = pow(a, 2) + pow(b, 2);
	// If the square has no fractional component and a + b + c = 1000, the triplet has been found
	if((sqrt(c) - int(sqrt(c)) == 0.0) && (a + b + sqrt(c)) == 1000)
	{
		return true;
	}
	return false;
}

Leave a Reply

Your email address will not be published. Required fields are marked *