|
| 1 | +""" |
| 2 | +== Carmichael Numbers == |
| 3 | +A number n is said to be a Carmichael number if it |
| 4 | +satisfies the following modular arithmetic condition: |
| 5 | +
|
| 6 | + power(b, n-1) MOD n = 1, |
| 7 | + for all b ranging from 1 to n such that b and |
| 8 | + n are relatively prime, i.e, gcd(b, n) = 1 |
| 9 | +
|
| 10 | +Examples of Carmichael Numbers: 561, 1105, ... |
| 11 | +https://en.wikipedia.org/wiki/Carmichael_number |
| 12 | +""" |
| 13 | + |
| 14 | + |
| 15 | +def gcd(a: int, b: int) -> int: |
| 16 | + if a < b: |
| 17 | + return gcd(b, a) |
| 18 | + if a % b == 0: |
| 19 | + return b |
| 20 | + return gcd(b, a % b) |
| 21 | + |
| 22 | + |
| 23 | +def power(x: int, y: int, mod: int) -> int: |
| 24 | + if y == 0: |
| 25 | + return 1 |
| 26 | + temp = power(x, y // 2, mod) % mod |
| 27 | + temp = (temp * temp) % mod |
| 28 | + if y % 2 == 1: |
| 29 | + temp = (temp * x) % mod |
| 30 | + return temp |
| 31 | + |
| 32 | + |
| 33 | +def isCarmichaelNumber(n: int) -> bool: |
| 34 | + b = 2 |
| 35 | + while b < n: |
| 36 | + if gcd(b, n) == 1 and power(b, n - 1, n) != 1: |
| 37 | + return False |
| 38 | + b += 1 |
| 39 | + return True |
| 40 | + |
| 41 | + |
| 42 | +if __name__ == "__main__": |
| 43 | + number = int(input("Enter number: ").strip()) |
| 44 | + if isCarmichaelNumber(number): |
| 45 | + print(f"{number} is a Carmichael Number.") |
| 46 | + else: |
| 47 | + print(f"{number} is not a Carmichael Number.") |
0 commit comments