From 8690b8823cfba59fbed2dbb36bc0e8c09cebbdcc Mon Sep 17 00:00:00 2001 From: Legoeggolas <55898978+Legoeggolas@users.noreply.github.com> Date: Sun, 28 Aug 2022 21:42:19 +0530 Subject: [PATCH] Optimize the solution for #37 --- challenges/C++/pythagorean_triplet/solution.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/challenges/C++/pythagorean_triplet/solution.cpp b/challenges/C++/pythagorean_triplet/solution.cpp index 13d6275..59181dd 100644 --- a/challenges/C++/pythagorean_triplet/solution.cpp +++ b/challenges/C++/pythagorean_triplet/solution.cpp @@ -8,11 +8,21 @@ std::array pythaTriplet() { std::array 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;