Golf the repeated totient function

05AB1E, 2 bytes

Code:

Explanation:

F   # Do the following n times:
 Õ  #   ..Calculate the totient

Uses the CP-1252 encoding. Try it online!.


Python 2, 84 78 70 bytes

n,x=input();exec('k=m=1;'+'x-=(x%k<m%k)*x/k;m*=k*k;k+=1;'*x)*n;print x

Thanks to @xnor for golfing off 8 bytes!

Test it on Ideone.

Background

By Euler's product formula,

Euler's product formula

where φ denotes Euler's totient function and p varies only over prime numbers.

To identify primes, we use a corollary of Wilson's theorem:

corollary of Wilson's theorem

How it works

After reading the input, we construct and execute a certain string. The executed code is roughly equivalent to the following.

r = range(x)
for _ in range(n):
    k = 1
    m = 1
    for _ in r:
        x -= (x % k < m % k) * x / k
        m *= k**2
        k += 1

The inner loop will set x = φ(x), so executing it n times stores the desired output in x.

At all times, the variable m will be equal to the square of the factorial of k - 1. In fact, we set k = 1 and m = 0!2 = 1 at the beginning of the inner loop.

k varies from its initial value 1 to the initial value of x and is incremented each time the sinner loop is executed. m is updated accordingly by multiplying it by the "old" value of k2.

For the actual calculation of x, recall that m%k will yield 1 if m is prime and 0 if not. This means that x%k<m%k will yield True if and only if both k is a prime number and x is divisible by k.

In this case, (x%k<m%k)*x/k yields x / k, and subtracting it from x replaces its previous value with x(1 - 1/k), as in Euler's product formula. Otherwise, (x%k<m%k)*x/k yields 0 and x remains unchanged.


Actually, 4 bytes

`▒`n

Try it online!

This program takes x as the first input, and n as the second input.

Explanation:

`▒`n
`▒`n  call the following function n times:
 ▒      totient(x)