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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
/* This script is part of radix_info.
Copyright (C) 2023 Adrien Hopkins
This program is free software: you can redistribute it and/or modify
it under the terms of version 3 of the GNU General Public License
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
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
}
|