summaryrefslogtreecommitdiff
path: root/factors/totative.go
blob: d1947b66dbbfd2062fe2297798a6788304c93e00 (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
32
33
package factors

// Totient calculates the number of numbers between 1 and n inclusive
// that are totatives of n (share no factors with n)
func Totient(n uint) uint {
	if n == 0 {
		return 0
	}

	primeFactorization := PrimeFactorize(n)
	num, denom := uint(1), uint(1)

	for p := range primeFactorization.exponents {
		num *= p - 1
		denom *= p
	}

	return num * (n / denom)
}

// TotativeDigits returns a slice containing every number between 1 and r
// inclusive that is a totative of r (shares no factors with r).
func TotativeDigits(r uint32) []uint32 {
	digits := make([]uint32, Totient(uint(r)))
	totativesFound := 0
	for d := uint32(1); d <= r; d++ {
		if gcd(d, r) == 1 {
			digits[totativesFound] = d
			totativesFound++
		}
	}
	return digits
}