summaryrefslogtreecommitdiff
path: root/factors/factorize.go
blob: 8e82b16140a8a9ade8f1bc1fdc4a4c1d54d6380e (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
package factors

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

	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
	}
	return factors
}