Skip to content

Commit

Permalink
feat(tricks): ordered reduced residue system
Browse files Browse the repository at this point in the history
Signed-off-by: Pouyan Heyratpour <[email protected]>
  • Loading branch information
pouyanh committed Dec 4, 2024
1 parent 8e116da commit e5cc0ce
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 11 deletions.
42 changes: 31 additions & 11 deletions tricks/mathx/arithmetic.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,21 +159,41 @@ func PrimitiveRootsWithRrs(n int) map[int][]int {

prr := make(map[int][]int)
for _, cp := range cpp {
mm := make([]int, 0, len(cpp)+1)
m := 1
for i := 1; i < n; i++ {
m = (m * cp) % n
mm = append(mm, m)

if m == 1 {
break
}
}

mm := orderedReducedResidueSystem(n, cp, make([]int, 0, len(cpp)+1))
if len(mm) == len(cpp)+1 {
prr[cp] = mm[:len(mm):len(mm)]
}
}

return prr
}

// OrderedReducedResidueSystem returns reduced residue system modulo n
// ordered by powers of g. If g is not a primitive root of n it returns nil
func OrderedReducedResidueSystem(n, g int) []int {
if !IsPrimitiveRoot(n, g) {
return nil
}

return orderedReducedResidueSystem(n, g, make([]int, 0, EulerTotient(n)))
}

// orderedReducedResidueSystem returns reduced residue system modulo n
// // ordered by powers of g which have to be a primitive root of n
func orderedReducedResidueSystem(n, pr int, rrs []int) []int {
if rrs == nil {
rrs = make([]int, 0, 10)
}

m := 1
for i := 1; i < n; i++ {
m = (m * pr) % n
rrs = append(rrs, m)

if m == 1 {
break
}
}

return rrs[:len(rrs):len(rrs)]
}
11 changes: 11 additions & 0 deletions tricks/mathx/arithmetic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -310,3 +310,14 @@ func TestPrimitiveRootsWithRrs(t *testing.T) {
}
}
}

func TestOrderedReducedResidueSystem(t *testing.T) {
assert.Equal(t, []int{2, 4, 3, 1}, mathx.OrderedReducedResidueSystem(5, 2))
assert.Equal(t, []int{3, 4, 2, 1}, mathx.OrderedReducedResidueSystem(5, 3))
assert.Equal(t, []int{
63, 10, 95, 100, 94, 37, 84, 49, 91, 62, 54, 85, 5, 101, 50, 47, 72, 42, 78, 99, 31, 27, 96, 56, 104, 25, 77, 36,
21, 39, 103, 69, 67, 48, 28, 52, 66, 92, 18, 64, 73, 105, 88, 87, 24, 14, 26, 33, 46, 9, 32, 90, 106, 44, 97, 12,
7, 13, 70, 23, 58, 16, 45, 53, 22, 102, 6, 57, 60, 35, 65, 29, 8, 76, 80, 11, 51, 3, 82, 30, 71, 86, 68, 4, 38, 40,
59, 79, 55, 41, 15, 89, 43, 34, 2, 19, 20, 83, 93, 81, 74, 61, 98, 75, 17, 1,
}, mathx.OrderedReducedResidueSystem(107, 63))
}

0 comments on commit e5cc0ce

Please sign in to comment.