Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculation of euler phi function

int phi (int n) {
    int result = n;
    for (int i=2; i*i<=n; ++i)
        if (n % i == 0) {
            while (n % i == 0)
                n /= i;
            result -= result / i;
        }
    if (n > 1)
        result -= result / n;
    return result;
}

I saw the above implementation of Euler phi function which is of the O(sqrt n).I don't get the fact of using i*i<=n in the for loop and need of changing n.It is said that it can be done in a time much smaller O (sqrt n) How? link (in Russian)

like image 347
DCoder Avatar asked Sep 29 '25 09:09

DCoder


1 Answers

i*i<=n is same as i<= sqrt(n) from which your iteration lasts only to order of sqrt(n).

Using the straight definition of Euler totient function you are supposed to find the prime numbers that divides n.

like image 130
Santosh Linkha Avatar answered Oct 02 '25 04:10

Santosh Linkha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!