Java – improve code that breaks down faster?

I want to finish this code faster It returns all the factors (prime) of a long number If longnumber is specific, it obviously takes a few minutes to execute@ H_ 301_ 7@

int div = 2;
String factors = "";

while (longNumer != 1)
{
    if (longNumer % div == 0)
    {
        longNumer /= div;
        factors += div + " ";
    }
    else { div++; }
}

//longNumber = 10,gives: 2 5. 
//longNumber = 150,gives: 3 5 7.
//longNumber = 10523,gives: 17 619.

Solution

For large numbers, you can use the sieve of Eratosthenes algorithm to first find prime numbers up to sqrt (n), and then you must check whether these prime numbers are factors

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>