Problem 236
Euler's Totient Function
Medium · 20 pts · Math, Number Theory
Problem
Euler's totient function phi(N) counts the integers from 1 to N that are coprime with N, meaning their greatest common divisor with N is 1. By definition phi(1) = 1. Print phi(N). Use the prime factorisation of N: phi(N) = N × (1 - 1/p) for every distinct prime p dividing N. In integers, start with result = N and, for each distinct prime factor p, do result = result / p × (p - 1). Trial division up to the square root of N finds the primes. The numbers in this problem can be larger than a 32-bit int can hold (about 2.1 × 10^9), so use a 64-bit integer type: long long in C++, long in Java (Python needs nothing special).
Input
A single integer N.
Output
Print phi(N).
Constraints
1 <= N <= 1000000000000
Example input
10
Example output
4
Explanation
Among 1 to 10, the numbers sharing no factor with 10 are 1, 3, 7 and 9, so phi(10) = 4. With the formula: 10 = 2 × 5, and 10 × 1/2 × 4/5 = 4.