Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Basics

Euler's Totient Function

Medium · Basics · Asked at Google, Amazon, Codenation

Print φ(n) — the number of integers from 1 to n that share no common factor with n other than 1 (that is, gcd(k, n) = 1).

Input

A single integer n.

Output

φ(n).

Constraints

φ(n) = n × Π (1 − 1/p) over the distinct primes p dividing n. Find the primes by trial division up to √n; for each prime p do result = result / p × (p − 1) (divide first to stay exact). A factor left over above √n is one more prime.

Example 1

Input

9

Output

6

Example 2

Input

1

Output

1

Hints

  1. φ is multiplicative, and for a prime power φ(p^k) = p^k − p^(k−1).
  2. Together: φ(n) = n · Π (1 − 1/p) over the distinct primes p dividing n.
  3. Trial division up to √n finds all the primes (one may remain above √n).

Approach

Set result = n. For p = 2, 3, … while p · p ≤ n: if p divides n, strip all factors p from n and apply result = result / p · (p − 1). If n > 1 afterwards, it is a prime factor too — apply the same step. Dividing before multiplying keeps the numbers exact and inside 64 bits.

Complexity: O(√n) time · O(1) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    long long n;
    cin >> n;
    long long res = n;
    for (long long p = 2; p * p <= n; p++) {
        if (n % p) continue;
        while (n % p == 0) n /= p;
        res = res / p * (p - 1);
    }
    if (n > 1) res = res / n * (n - 1);
    cout << res << "\n";
    return 0;
}

Python solution

n = int(input())
res = n
p = 2
while p * p <= n:
    if n % p == 0:
        while n % p == 0:
            n //= p
        res = res // p * (p - 1)
    p += 1
if n > 1:
    res = res // n * (n - 1)
print(res)

Java solution

import java.util.*;

public class Main {
    public static void main(String[] args) {
        long n = new Scanner(System.in).nextLong();
        long res = n;
        for (long p = 2; p * p <= n; p++) {
            if (n % p != 0) continue;
            while (n % p == 0) n /= p;
            res = res / p * (p - 1);
        }
        if (n > 1) res = res / n * (n - 1);
        System.out.println(res);
    }
}

Solve Euler's Totient Function online · All practice problems