Skip to content

Commit f0d1a42

Browse files
Roy-Shubhajitpre-commit-ci[bot]cclauss
authored
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 <[email protected]>
1 parent 0a3433e commit f0d1a42

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

maths/carmichael_number.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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

Comments
 (0)