Examples

ϕ(1)=1(1)ϕ(2)=1(1)ϕ(3)=2(1,2)ϕ(4)=2(1,3)ϕ(5)=4(1,2,3,4)ϕ(6)=2(1,5)

Properties

The following three properties will allow us to calculate it for any number:

  • if p is a prime then ϕ(p)=p1

Proof: obviously since p is a prime the only divisors that it has are 1 and p but gcd(1,p)=1 so 1 falls under the definition of the euler function, therefore the only divisor valid for the euler function for the case above is p

  • if p is a prime and k1 a positive integer then ϕ(pk)=pkpk1

Proof: Since the multiples of p that are less than or equal to pk are: p,2p,3p,,pk1ppk we can see that in total there are pk1 numbers therefore the other pkpk1 are relative coprime to pk

Example:

ϕ(24)

multiples of 2 less than 24 are 12,22,32,42,52,62,72,82 which are in total 23 elements, therefore the other 2423 are relative prime to 24

  • if a and b are relatively prime then ϕ(ab)=ϕ(a)ϕ(b)

Computation

Given a number n let’s decompose it into prime factors (factorization):

n=p1a1p2a2...pkak

Applying the euler function we get:

ϕ(n)=ϕ(p1a1)ϕ(p2a2)...ϕ(pkak)=(p1a1p1a11)(p2a2p2a21)...(pkakpkak1)=(p1a1p1a1p1)(p2a2p2a2p2)...(pkakpkakpk)=p1a1(11p1)p2a2(11p2)...pkak(11pk)=p1a1p2a2...pkak(11p1)(11p2)...(11pk)=n(11p1)(11p2)...(11pk)=np|n(11p)

Implementation

Time complexity: O(n) Space: O(1)

int phi(int n) {
  int result = n;
  for (int i = 2; i * i <= n; i += 1) {
    // if `i` is a divisor of `n`
    if (n % i == 0) {
      // divide it by `i^k` so that it's no longer divisible by `i`
      while (n % i == 0) {
        n /= i;
      }
      // all the multiples of `i` are coprime to n, the number of
      // multiples is equal to `i * k` <= n, therefore `k <= n / i`
      result -= result / i;
    }
  }
  if (n > 1) {
    result -= result / n;
  }
  return result;
}

Problems

10179 - Irreducable Basic Fractions 10299 - Relatives 11327 - Enumerating Rational Numbers