Lesson 12 of 15
Euler's Totient Function
Euler's Totient Function
Euler's totient function (phi of n) counts how many integers in are coprime to (i.e., share no common factor with other than 1):
Examples
- : the numbers are coprime to 12
- : all of are coprime to 7 (7 is prime)
- For any prime :
Computing the Totient
A direct approach: count from 1 to using the GCD.
def gcd(a, b):
while b:
a, b = b, a % b
return a
def euler_totient(n):
return sum(1 for k in range(1, n + 1) if gcd(k, n) == 1)
print(euler_totient(12)) # 4
There is also a product formula using the prime factorization of :
Euler's Theorem
If , then:
This generalizes Fermat's Little Theorem (which applies only when is prime) and is the theoretical foundation of RSA encryption.
Totient Sum
The sum of the totient over all integers up to has a neat relation to counting coprime pairs:
def totient_sum(n):
return sum(euler_totient(k) for k in range(1, n + 1))
print(totient_sum(5)) # 10
Your Task
Implement euler_totient(n) and totient_sum(n) using the GCD-based approach.
Python runtime loading...
Loading...
Click "Run" to execute your code.