Skip to content

Commit 6a99cd7

Browse files
algorithm: Liouville lambda function (TheAlgorithms#540)
1 parent 1acfe4c commit 6a99cd7

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

math/liouville.go

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// liouville.go
2+
// description: Returns λ(n)
3+
// details:
4+
// For any positive integer n, define λ(n) as the sum of the primitive nth roots of unity.
5+
// It has values in {−1, 1} depending on the factorization of n into prime factors:
6+
// λ(n) = +1 if n is a positive integer with an even number of prime factors.
7+
// λ(n) = −1 if n is a positive integer with an odd number of prime factors.
8+
// wikipedia: https://en.wikipedia.org/wiki/Liouville_function
9+
// author: Akshay Dubey (https://github.com/itsAkshayDubey)
10+
// see liouville_test.go
11+
12+
package math
13+
14+
import (
15+
"errors"
16+
17+
"github.com/TheAlgorithms/Go/math/prime"
18+
)
19+
20+
var ErrNonZeroArgsOnly error = errors.New("arguments cannot be zero")
21+
22+
// Lambda is the liouville function
23+
// This function returns λ(n) for given number
24+
func LiouvilleLambda(n int) (int, error) {
25+
switch {
26+
case n < 0:
27+
return 0, ErrPosArgsOnly
28+
case n == 0:
29+
return 0, ErrNonZeroArgsOnly
30+
case len(prime.Factorize(int64(n)))%2 == 0:
31+
return 1, nil
32+
default:
33+
return -1, nil
34+
}
35+
}

math/liouville_test.go

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// liouville_test.go
2+
// description: Returns λ(n)
3+
// author: Akshay Dubey (https://github.com/itsAkshayDubey)
4+
// see liouville.go
5+
6+
package math_test
7+
8+
import (
9+
"testing"
10+
11+
"github.com/TheAlgorithms/Go/math"
12+
)
13+
14+
func TestLiouvilleLambda(t *testing.T) {
15+
var tests = []struct {
16+
name string
17+
n int
18+
expectedValue int
19+
expectedError error
20+
}{
21+
{"n = 10", 10, 1, nil},
22+
{"n = 11", 11, -1, nil},
23+
{"n = -1", -1, 0, math.ErrPosArgsOnly},
24+
{"n = 0", 0, 0, math.ErrNonZeroArgsOnly},
25+
}
26+
for _, test := range tests {
27+
t.Run(test.name, func(t *testing.T) {
28+
result, err := math.LiouvilleLambda(test.n)
29+
if result != test.expectedValue || test.expectedError != err {
30+
t.Errorf("expected error: %s, got: %s; expected value: %v, got: %v", test.expectedError, err, test.expectedValue, result)
31+
}
32+
})
33+
}
34+
}
35+
func BenchmarkLiouvilleLambda(b *testing.B) {
36+
for i := 0; i < b.N; i++ {
37+
_, _ = math.LiouvilleLambda(65536)
38+
}
39+
}

0 commit comments

Comments
 (0)