Skip to content

Commit

Permalink
Optimize the solution for ademclk#37
Browse files Browse the repository at this point in the history
  • Loading branch information
Legoeggolas committed Aug 28, 2022
1 parent 9075ef1 commit 8690b88
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion challenges/C++/pythagorean_triplet/solution.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,21 @@ std::array<int, 3> pythaTriplet() {
std::array<int, 3> triplet = {0, 0, 0};
bool found = false;
// since a + b + c = 1000
// and a < b < c
// the max we can go is a = 332, b = 333, c = 334
for (int a = 1; a <= 332 && !found; a++) {
for (int b = a + 1; b <= 333 + (332 - a) && !found; b++) {
// the maximum b can reach is when a = 1
// then b = 999 - c_min
// and since b < c they must be consecutive numbers
// which nets b = 499
for (int b = a + 1; b <= 499 && !found; b++) {
int c = 1000 - (a + b);

// b < c always
if (c <= b) {
break;
}

if (sq(a) + sq(b) == sq(c)) {
triplet = {a, b, c};
found = true;
Expand Down

0 comments on commit 8690b88

Please sign in to comment.