From 165e55184e79553c74b9c9056fd46f1b37a2b5d9 Mon Sep 17 00:00:00 2001 From: Adrien Hopkins Date: Tue, 19 Sep 2023 11:10:48 -0500 Subject: factors: refactor code to improve readability --- factors/prime_factorization.go | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'factors/prime_factorization.go') diff --git a/factors/prime_factorization.go b/factors/prime_factorization.go index f91a2cf..d9f11e5 100644 --- a/factors/prime_factorization.go +++ b/factors/prime_factorization.go @@ -19,17 +19,13 @@ func PrimeFactorize(n uint) PrimeFactorization { return PrimeFactorization{map[uint]uint{0: 1}} } - unfactored := n // number with all found factors removed (divided) + unfactored := n exponents := make(map[uint]uint) - // try each factor starting at 2 - // if unfactored is divisible divide out until it isn't - for f := uint(2); f*f <= unfactored; { - if unfactored%f == 0 { - unfactored /= f - exponents[f] += 1 - } else { - f += 1 + for possibleFactor := uint(2); possibleFactor*possibleFactor <= unfactored; possibleFactor++ { + for unfactored%possibleFactor == 0 { + unfactored /= possibleFactor + exponents[possibleFactor] += 1 } } @@ -90,3 +86,7 @@ func (factors PrimeFactorization) String() string { } return strings.Join(parts, " × ") } + +func isPrime(p uint) bool { + return p > 1 && PrimeFactorize(p).Exponent(p) == 1 +} -- cgit v1.2.3