From 4ce8ad9ce6e554360089e77e088df6dd8b4a69df Mon Sep 17 00:00:00 2001 From: Akshay Dubey <38462415+itsAkshayDubey@users.noreply.github.com> Date: Tue, 15 Nov 2022 22:58:49 +0530 Subject: [PATCH] algorithm: Liouville lambda function (#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> --- maths/liouville_lambda.py | 45 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 maths/liouville_lambda.py diff --git a/maths/liouville_lambda.py b/maths/liouville_lambda.py new file mode 100644 index 000000000..5993efa42 --- /dev/null +++ b/maths/liouville_lambda.py @@ -0,0 +1,45 @@ +""" +== Liouville Lambda Function == +The Liouville Lambda function, denoted by λ(n) +and λ(n) is 1 if n is the product of an even number of prime numbers, +and -1 if it is the product of an odd number of primes. + +https://en.wikipedia.org/wiki/Liouville_function +""" + +# Author : Akshay Dubey (https://github.com/itsAkshayDubey) +from maths.prime_factors import prime_factors + + +def liouville_lambda(number: int) -> int: + """ + This functions takes an integer number as input. + returns 1 if n has even number of prime factors and -1 otherwise. + >>> liouville_lambda(10) + 1 + >>> liouville_lambda(11) + -1 + >>> liouville_lambda(0) + Traceback (most recent call last): + ... + ValueError: Input must be a positive integer + >>> liouville_lambda(-1) + Traceback (most recent call last): + ... + ValueError: Input must be a positive integer + >>> liouville_lambda(11.0) + Traceback (most recent call last): + ... + TypeError: Input value of [number=11.0] must be an integer + """ + if not isinstance(number, int): + raise TypeError(f"Input value of [number={number}] must be an integer") + if number < 1: + raise ValueError("Input must be a positive integer") + return -1 if len(prime_factors(number)) % 2 else 1 + + +if __name__ == "__main__": + import doctest + + doctest.testmod()