Java – prime factorization of large numbers
•
Java
I want to find the prime factorization of large numbers less than 10 ^ 12
public static List<Long> primeFactors(long numbers) {
long n = numbers;
List<Long> factors = new ArrayList<Long>();
for (long i = 2; i <= n / i; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
if (n > 1) {
factors.add(n);
}
return factors;
}
First, what is the complexity of the above algorithm? It's hard for me to find it?
It will also be too slow for numbers with large prime numbers
Is there a better algorithm, or how to optimize it?
Solution
If you want to decompose many large numbers, you might better find a prime number up to sqrt (n) (for example, use sieve of erasthenes) Then you must only check whether those primes are factors, not test all I < = sqrt (n)
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
二维码
