Calculating Eulers Totient Function for very large numbers JAVA

早过忘川 提交于 2019-12-08 18:28:31
eh9

The algorithm you are trying to write is equivalent to factoring the argument n, which means you should expect it to run forever, practically speaking until either your computer dies or you die. See this post in mathoverflow for more information: How hard is it to compute the Euler totient function?.

If, on the other hand, you want the value of the totient for some large number for which you have the factorization, pass the argument as sequence of (prime, exponent) pairs.

There is a formula for the totient function, which required the prime factorization of n. Look here.

The formula is:

phi(n) = n * (p1 - 1) / p1 * (p2 - 1) / p2 ....
were p1, p2, etc. are all the prime divisors of n.

Note that you only need BigInteger, not floating point, because the division is always exact.

So now the problem is reduced to finding all prime factors, which is better than iteration.

Here is the whole solution:

int n;  //this is the number you want to find the totient of
int tot = n; //this will be the totient at the end of the sample
for (int p = 2; p*p <= n; p++)
{
    if (n%p==0)
    {
        tot /= p;
        tot *= (p-1);
        while ( n % p == 0 ) 
            n /= p;
    }
}
if ( n > 1 ) { // now n is the largest prime divisor
    tot /= n;
    tot *= (n-1);
}

The etfBig method has a problem.
Euler's product formula is n*((factor-1)/factor) for all factors. Note: Petar's code has it as:

tot /= p; tot *= (p-1);

In the etfBig method, replace result = result.divide(i); with

result = result.multiply(i.subtract(BigInteger.ONE)).divide(i);

Testing from 2 to 200 then produces the same results as the regular algorithm.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!