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/factorize.go | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) (limited to 'factors/factorize.go') diff --git a/factors/factorize.go b/factors/factorize.go index 8e82b16..9aa43a7 100644 --- a/factors/factorize.go +++ b/factors/factorize.go @@ -10,18 +10,20 @@ func Factors(n uint) []uint { primeFactorization := PrimeFactorize(n) factors := []uint{1} - for p, e := range primeFactorization.exponents { - next_factors := make([]uint, 0, len(factors)*int(e)) - for _, factor := range factors { - for i := uint(0); i <= e; i++ { - multiplier := uint(1) - for j := uint(0); j < i; j++ { - multiplier *= p - } - next_factors = append(next_factors, factor*multiplier) - } - } - factors = next_factors + for prime, exponent := range primeFactorization.exponents { + factors = expandFactors(factors, prime, exponent) } return factors } + +// expandFactors takes a slice and returns a new slice where every factor +// f in the original slice is replaced with f, f*p, f*p^2, ..., f*p^e. +func expandFactors(factors []uint, prime, exponent uint) []uint { + nextFactors := make([]uint, 0, len(factors)*int(exponent)) + for _, factor := range factors { + for i := uint(0); i <= exponent; i++ { + nextFactors = append(nextFactors, factor*uintpow(prime, i)) + } + } + return nextFactors +} -- cgit v1.2.3