commit e3aa186b08e7ccdf1f4b6b89aa1724864df0bff7 parent 4cf43d5967c68f9b6ac3e1ae3163802f1a7e9426 Author: mpizzzle <m@michaelpercival.xyz> Date: Sun, 27 Sep 2020 22:40:26 +0100 refactoring both loops into one Diffstat:
| M | Euler_95.cpp | | | 34 | ++++++++++++++-------------------- |
1 file changed, 14 insertions(+), 20 deletions(-)
diff --git a/Euler_95.cpp b/Euler_95.cpp @@ -11,45 +11,39 @@ int Euler::AmicableChains() for (int i = 2; i < root; ++i) { for (int j = 2; i * j <= one_million; ++j) { divisors[i * j] += i + ((j >= root) ? j : 0); - } + } } for (int n = 1; n <= one_million; ++n) { int length = 0; int candidate = one_million; int slow_ptr = n, fast_ptr = n; + bool loop_found = false; while(fast_ptr > 1 && slow_ptr <= one_million && fast_ptr <= one_million) { + length += loop_found; fast_ptr = divisors[fast_ptr]; if (fast_ptr <= 1 || fast_ptr > one_million) { break; } - if (slow_ptr == fast_ptr) { - while (true) { - length++; - fast_ptr = divisors[fast_ptr]; - - if (slow_ptr < candidate) { - candidate = slow_ptr; - } - - if (slow_ptr == fast_ptr) { - if (length > longest) { - solution = candidate; - longest = length; - } + if (loop_found && slow_ptr < candidate) { + candidate = slow_ptr; + } - divisors[candidate] = 1; - break; + if (slow_ptr == fast_ptr) { + if (loop_found) { + if (length > longest) { + solution = candidate; + longest = length; } - slow_ptr = divisors[slow_ptr]; - fast_ptr = divisors[fast_ptr]; + divisors[candidate] = 1; + break; } - break; + loop_found = true; } slow_ptr = divisors[slow_ptr];