summaryrefslogtreecommitdiff
path: root/factors/factorize.go
blob: 16cd8107c03e2f560edaef2675ffee04ab3cb409 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package factors

// Factors returns a number's factors as a slice.
// The slice is not guaranteed to be in sorted order.
//
// Because every number is a factor of zero, Factors(0) panics.
func Factors(n uint) []uint {
	if n == 0 {
		panic("Cannot get factors of 0!")
	}

	primeFactorization := PrimeFactorize(n)

	factors := []uint{1}
	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
}