Skip to content

Commit

Permalink
feat: Add mobius function (TheAlgorithms#532)
Browse files Browse the repository at this point in the history
  • Loading branch information
itsAkshayDubey authored Sep 9, 2022
1 parent 72ff3a7 commit f850556
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
38 changes: 38 additions & 0 deletions math/mobius.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// mobius.go
// description: Returns μ(n)
// details:
// For any positive integer n, define μ(n) as the sum of the primitive nth roots of unity.
// It has values in {−1, 0, 1} depending on the factorization of n into prime factors:
// μ(n) = +1 if n is a square-free positive integer with an even number of prime factors.
// μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors.
// μ(n) = 0 if n has a squared prime factor.
// wikipedia: https://en.wikipedia.org/wiki/M%C3%B6bius_function
// author: Akshay Dubey (https://github.com/itsAkshayDubey)
// see mobius_test.go

package math

import (
"github.com/TheAlgorithms/Go/math/prime"
)

// Mu is the Mobius function
// This function returns μ(n) for given number
func Mu(n int) int {
if n <= 1 {
return 1
}
var primeFactorCount int
for i := 1; i <= n; i++ {
if n%i == 0 && prime.OptimizedTrialDivision(int64(i)) {
if n%(i*i) == 0 {
return 0
}
primeFactorCount += 1
}
}
if primeFactorCount%2 == 0 {
return 1
}
return -1
}
41 changes: 41 additions & 0 deletions math/mobius_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// mobius_test.go
// description: Returns μ(n)
// author: Akshay Dubey (https://github.com/itsAkshayDubey)
// see mobius.go

package math_test

import (
"testing"

algmath "github.com/TheAlgorithms/Go/math"
)

func TestMu(t *testing.T) {
var tests = []struct {
n int
expected int
}{
{-1, 1},
{0, 1},
{2, -1},
{3, -1},
{95, 1},
{97, -1},
{98, 0},
{99, 0},
{100, 0},
}
for _, test := range tests {
result := algmath.Mu(test.n)
t.Log(test.n, " ", result)
if result != test.expected {
t.Errorf("Wrong result! Expected:%v, returned:%v ", test.expected, result)
}
}
}
func BenchmarkMu(b *testing.B) {
for i := 0; i < b.N; i++ {
algmath.Mu(65536)
}
}

0 comments on commit f850556

Please sign in to comment.