Reduce the number of System.out.println calls may give a little speedup:
public class IntegerFactoriseFive {
public static void main(String[] args)
{
StringBuilder sb= new StringBuilder();
long n = 600851475143L;
for (long i = 2; i <= n; i++)
{
if (n % i==0)
{
sb.append(i).append('\n');
n /= i;
i = 2;
}
}
System.out.println(sb.toString);
}
}
You can also modify your algorithm.
- If a number can not be divided by 2 it can also not be divided by any even number. So you can check2 and than only the odd numbers.
- you can make a list of all little prime numbers and check these and from the point where you have not the primes, try all odd numbers
- you can stop checking at sqrt(n) but that is quite expensive to calculate. Not so good, but still halves the work, stop at
n/2.