From 7b4de733a7cf5e03e9eb549cc7ac661cb10b465a Mon Sep 17 00:00:00 2001 From: Chip Hogg Date: Tue, 19 Nov 2024 18:10:57 -0500 Subject: [PATCH] Guarantee return value is prime --- au/code/au/utility/factoring.hh | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/au/code/au/utility/factoring.hh b/au/code/au/utility/factoring.hh index af0c2dd9..e8bf7cfd 100644 --- a/au/code/au/utility/factoring.hh +++ b/au/code/au/utility/factoring.hh @@ -65,7 +65,7 @@ constexpr std::uintmax_t find_pollard_rho_factor(std::uintmax_t n) { ++cycle_length; factor = gcd(n, absolute_diff(tortoise, hare)); } - if (factor > 1u && factor < n) { + if (factor < n) { return factor; } } @@ -112,7 +112,11 @@ constexpr std::uintmax_t find_prime_factor(std::uintmax_t n) { return n; } - return find_pollard_rho_factor(n); + auto factor = find_pollard_rho_factor(n); + while (!is_prime(factor)) { + factor = find_pollard_rho_factor(factor); + } + return factor; } // Find the largest power of `factor` which divides `n`.