From f0d1a42deb146bebcdf7b1b2ec788c815ede452a Mon Sep 17 00:00:00 2001 From: Shubhajit Roy <81477286+shubhajitroy123@users.noreply.github.com> Date: Wed, 12 Oct 2022 12:52:23 +0530 Subject: [PATCH] Python program for Carmicheal Number (#6864) * Add files via upload Python program to determine whether a number is Carmichael Number or not. * Rename Carmichael Number.py to carmichael number.py * Rename carmichael number.py to carmichael_number.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update carmichael_number.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Create carmichael_number.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update maths/carmichael_number.py Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss --- maths/carmichael_number.py | 47 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 maths/carmichael_number.py diff --git a/maths/carmichael_number.py b/maths/carmichael_number.py new file mode 100644 index 000000000..09a4fedfb --- /dev/null +++ b/maths/carmichael_number.py @@ -0,0 +1,47 @@ +""" +== Carmichael Numbers == +A number n is said to be a Carmichael number if it +satisfies the following modular arithmetic condition: + + power(b, n-1) MOD n = 1, + for all b ranging from 1 to n such that b and + n are relatively prime, i.e, gcd(b, n) = 1 + +Examples of Carmichael Numbers: 561, 1105, ... +https://en.wikipedia.org/wiki/Carmichael_number +""" + + +def gcd(a: int, b: int) -> int: + if a < b: + return gcd(b, a) + if a % b == 0: + return b + return gcd(b, a % b) + + +def power(x: int, y: int, mod: int) -> int: + if y == 0: + return 1 + temp = power(x, y // 2, mod) % mod + temp = (temp * temp) % mod + if y % 2 == 1: + temp = (temp * x) % mod + return temp + + +def isCarmichaelNumber(n: int) -> bool: + b = 2 + while b < n: + if gcd(b, n) == 1 and power(b, n - 1, n) != 1: + return False + b += 1 + return True + + +if __name__ == "__main__": + number = int(input("Enter number: ").strip()) + if isCarmichaelNumber(number): + print(f"{number} is a Carmichael Number.") + else: + print(f"{number} is not a Carmichael Number.")