MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / totient

Function totient

maths/eulers_totient.py:2–35  ·  view source on GitHub ↗

>>> n = 10 >>> totient_calculation = totient(n) >>> for i in range(1, n): ... print(f"{i} has {totient_calculation[i]} relative primes.") 1 has 0 relative primes. 2 has 1 relative primes. 3 has 2 relative primes. 4 has 2 relative primes. 5 has 4 relative prim

(n: int)

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected