Skip to content

Commit 4ce8ad9

Browse files
algorithm: Liouville lambda function (TheAlgorithms#7986)
* feat: Add liouville lambda function * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * refactor: Refactor if-else block * refactor: Refactor error handling for -ve numbers * refactor: Remove # doctest: +NORMALIZE_WHITESPACE Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 3bf86b9 commit 4ce8ad9

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

maths/liouville_lambda.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""
2+
== Liouville Lambda Function ==
3+
The Liouville Lambda function, denoted by λ(n)
4+
and λ(n) is 1 if n is the product of an even number of prime numbers,
5+
and -1 if it is the product of an odd number of primes.
6+
7+
https://en.wikipedia.org/wiki/Liouville_function
8+
"""
9+
10+
# Author : Akshay Dubey (https://github.com/itsAkshayDubey)
11+
from maths.prime_factors import prime_factors
12+
13+
14+
def liouville_lambda(number: int) -> int:
15+
"""
16+
This functions takes an integer number as input.
17+
returns 1 if n has even number of prime factors and -1 otherwise.
18+
>>> liouville_lambda(10)
19+
1
20+
>>> liouville_lambda(11)
21+
-1
22+
>>> liouville_lambda(0)
23+
Traceback (most recent call last):
24+
...
25+
ValueError: Input must be a positive integer
26+
>>> liouville_lambda(-1)
27+
Traceback (most recent call last):
28+
...
29+
ValueError: Input must be a positive integer
30+
>>> liouville_lambda(11.0)
31+
Traceback (most recent call last):
32+
...
33+
TypeError: Input value of [number=11.0] must be an integer
34+
"""
35+
if not isinstance(number, int):
36+
raise TypeError(f"Input value of [number={number}] must be an integer")
37+
if number < 1:
38+
raise ValueError("Input must be a positive integer")
39+
return -1 if len(prime_factors(number)) % 2 else 1
40+
41+
42+
if __name__ == "__main__":
43+
import doctest
44+
45+
doctest.testmod()

0 commit comments

Comments
 (0)