public class factorize {
public static void f(int n) {
int i = 2;
while( n > 1) {
if (n%i == 0) {
System.out.println("Factors " + i);
n = n / i;
}
else {
i++;
}
}
}
Hello, I am doing in java a function of factorize but it takes many times to excute,I try to see on the internet some theorems but the result is the same. Can you advise me some algorithms to excute this factorize as fast as possibile? this code takes like 2 mins.
-
1If i^2 > n, you're done and n is prime.Louis Wasserman– Louis Wasserman2015年03月23日 19:51:32 +00:00Commented Mar 23, 2015 at 19:51
-
1What is c? I dont see a declaration.IdusOrtus– IdusOrtus2015年03月23日 19:52:31 +00:00Commented Mar 23, 2015 at 19:52
-
The easiest way to optimize this would be to remove IO. Don't print anything until the method is complete. IO is expensive.EyeOfTheHawks– EyeOfTheHawks2015年03月23日 21:25:46 +00:00Commented Mar 23, 2015 at 21:25
1 Answer 1
Try this:
public static void f(int n) {
int i = 2;
while(i*i <= n) {
if (n%i == 0) {
System.out.println("Factors " + i);
n = n / i;
}
else {
i++;
}
}
if (n > 1) {
System.out.println("Factors " + n);
}
}
This works because you can only have a single prime factor larger than sqrt(n)
: if you had two, their product would exceed n
, since sqrt(n)*sqrt(n) = n
. So it suffices to check those and then if n > 1
, that remaining n
is another prime factor.
Note: 2732983441203969650
is a large number that will not fit in an int
. You should consider using a long
if you want your algorithm to work for it. Note that its square root is also very large, and so the algorithm might still be very slow. For such large numbers, factorization is very hard. One algorithm you could try that will probably work for 64 bit numbers in decent time is Pollard's Rho algorithm.
Other things you can optimize in your code:
Check
2
separately and then only check divisibility by odd numbers;Use the Sieve of Eratosthenes to generate primes lower than the square root of
n
and check for divisibility against those primes.
4 Comments
sqrt(n)
. i <= sqrt(n) => i*i <= n
.i < 0
)