Skip to content

Commit 74aeaa3

Browse files
Abhijitpatil19cclauss
authored andcommitted
Code for Eulers Totient function (#1229)
* Create eulersTotient.py * Rename eulersTotient.py to eulers_totient.py * Update eulers_totient.py
1 parent 4dca957 commit 74aeaa3

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

maths/eulers_totient.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Eulers Totient function finds the number of relative primes of a number n from 1 to n
2+
def totient(n: int) -> list:
3+
is_prime = [True for i in range(n + 1)]
4+
totients = [i - 1 for i in range(n + 1)]
5+
primes = []
6+
for i in range(2, n + 1):
7+
if is_prime[i]:
8+
primes.append(i)
9+
for j in range(0, len(primes)):
10+
if i * primes[j] >= n:
11+
break
12+
is_prime[i * primes[j]] = False
13+
14+
if i % primes[j] == 0:
15+
totients[i * primes[j]] = totients[i] * primes[j]
16+
break
17+
18+
totients[i * primes[j]] = totients[i] * (primes[j] - 1)
19+
20+
return totients
21+
22+
23+
def test_totient() -> None:
24+
"""
25+
>>> n = 10
26+
>>> totient_calculation = totient(n)
27+
>>> for i in range(1, n):
28+
... print(f"{i} has {totient_calculation[i]} relative primes.")
29+
1 has 0 relative primes.
30+
2 has 1 relative primes.
31+
3 has 2 relative primes.
32+
4 has 2 relative primes.
33+
5 has 4 relative primes.
34+
6 has 2 relative primes.
35+
7 has 6 relative primes.
36+
8 has 4 relative primes.
37+
9 has 6 relative primes.
38+
"""
39+
pass
40+
41+
42+
if __name__ == "__main__":
43+
import doctest
44+
45+
doctest.testmod()

0 commit comments

Comments
 (0)