summaryrefslogtreecommitdiff
path: root/factors/factorize.go
diff options
context:
space:
mode:
Diffstat (limited to 'factors/factorize.go')
-rw-r--r--factors/factorize.go27
1 files changed, 27 insertions, 0 deletions
diff --git a/factors/factorize.go b/factors/factorize.go
new file mode 100644
index 0000000..2f7368a
--- /dev/null
+++ b/factors/factorize.go
@@ -0,0 +1,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
+}