C++ Implementation of Problem 9

View source code here on GitHub!

Includes

Solution

uint64_t p0009()
int main(int argc, char const *argv[])

Note

This function is only present in the Python test runner, or when compiling as a standalone program.

 1/*
 2Project Euler Problem 9
 3
 4This was fairly short to code, but it took me a minute to figure out how to deal with the lack of multi-loop breaking
 5
 6Problem:
 7
 8A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
 9a2 + b2 = c2
10
11For example, 32 + 42 = 9 + 16 = 25 = 52.
12
13There exists exactly one Pythagorean triplet for which a + b + c = 1000.
14Find the product abc.
15*/
16#ifndef EULER_P0009
17#define EULER_P0009
18#include <stdint.h>
19#include <iostream>
20#include "include/macros.hpp"
21
22uint64_t EMSCRIPTEN_KEEPALIVE p0009() {
23    uint64_t answer = 0;
24    for (uint32_t c = 3; !answer && c < 1000; c++)
25        for (uint32_t b = 2; b < c; b++) {
26            uint32_t a = 1000 - c - b;
27            if (a < b && a*a + b*b == c*c) {
28                answer = (uint64_t) a * b * c;
29                break;
30            }
31        }
32    return answer;
33}
34
35PROGRAM_TAIL(p0009)
36#endif

Tags: pythagorean-triple