I want to find the prime factorization of large numbers less than 10^12. I got this code (in java):
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 of all what is the complexity of the above algorithm ??I am having difficulties finding it ??
Also it will be too slow for large numbers that are prime .
Is there are better algorithm , or else how to optimize this algo ??
The complexity is
O(sqrt(n))
. There is no sense in checking numbers aftersqrt(n)
.This means that for
10^12
, it will take at most1 000 000
iterations, which is not slow.Factorising large numbers is hard problem which is partly why encryption algos use factors of large prime numbers to make the encryption difficult to crack.
prints
If you replace Long.MAX_VALUE with 1000000000000L they all factorize under 20 ms.
If you want to factorize many large numbers, then you might be better off first finding the prime numbers up to
sqrt(n)
(e.g. using Sieve of Eratosthenes). Then you have to check only whether those prime numbers are factors instead of testing alli <= sqrt(n)
.A better algorithm might be the following for searching for primes (my java is rusty, so some tweaking will probably be needed to get it to compile).