Skip to content

Commit

Permalink
feat(tricks): coprimes list
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 cd1859f commit 0637bd8
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
18 changes: 18 additions & 0 deletions tricks/mathx/arithmetic.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,24 @@ func PrimeFactors(n int) []int {
return ff[:len(ff):len(ff)]
}

// CoprimesInRange returns list of all natural numbers in closed range [from, to]
// which are coprime to the given number (n)
func CoprimesInRange(n, from, to int) []int {
cpp := make([]int, 0, 10)
for i := from; i <= to; i++ {
if Gcd(n, i) == 1 {
cpp = append(cpp, i)
}
}

return cpp[:len(cpp):len(cpp)]
}

// MinorCoprimes returns list of all natural numbers which are less than the given number (n) and coprime to it
func MinorCoprimes(n int) []int {
return CoprimesInRange(n, 1, n-1)
}

// NextPrime returns next prime number greater than the given number (n)
func NextPrime(n int) int {
if n < 1 {
Expand Down
10 changes: 10 additions & 0 deletions tricks/mathx/arithmetic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,16 @@ func TestPrimes(t *testing.T) {
assert.Equal(t, []int{}, mathx.PrimeFactors(-127))
}

func TestCoprimesInRange(t *testing.T) {
assert.Equal(t, []int{3, 7}, mathx.CoprimesInRange(10, 2, 7))
assert.Equal(t, []int{7, 9, 11, 13, 17, 19}, mathx.CoprimesInRange(10, 5, 20))
}

func TestMinorCoprimes(t *testing.T) {
assert.Equal(t, []int{1, 5}, mathx.MinorCoprimes(6))
assert.Equal(t, []int{1, 3, 7, 9}, mathx.MinorCoprimes(10))
}

func TestNextPrime(t *testing.T) {
assert.Equal(t, 2, mathx.NextPrime(0))
assert.Equal(t, 2, mathx.NextPrime(1))
Expand Down

0 comments on commit 0637bd8

Please sign in to comment.