Project Euler Problem 9

December 22, 2011

I’ve been having some fun doing the first few problems of Project Euler and figured I’d share my solution to problem 9 here.

The Problem
A Pythagorean triplet is a set of three natural numbers, a b c, for which,a^2 + b^2 = c^2
There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.

The Solution
This is pretty basic and inefficient, but I decided to loop through a and b, calculating c from the difference.

#include 
using namespace std;

int main () {

        for(int a = 1; a < 1000; a++) {
                for(int b = 1; b < 1000; b++) {
                        cout << "a: " << a << " b: " << b << " c: " << (1000 - a - b) << " a^2 + b^2: " << (a * a + b * b) << " c^2: " << (1000 - a - b) * (1000 - a - b) << endl;
                        if(a * a + b * b == (1000 - a - b) * (1000 - a - b)) {
                                return (0);
                        }
                }
        }
        return (0);
}

There you have it, the program stops at a^2 + b^2 = c^2 where c = (1000 – a – b). I then took a*b*c to get the answer.

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive