I am working on a prime factorization program implemented in Java. The goal is to find the largest prime factor of 600851475143 (Project Euler problem 3). I think I have m
For those answers which use a method isPrime(int) : boolean
, there is a faster algorithm than the one previously implemented (which is something like)
private static boolean isPrime(long n) { //when n >= 2
for (int k = 2; k < n; k++)
if (n % k == 0) return false;
return true;
}
and it is this:
private static boolean isPrime(long n) { //when n >= 2
if (n == 2 || n == 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int k = 1; k <= (Math.floor(Math.sqrt(n)) + 1) / 6; k++)
if (n % (6 * k + 1) == 0 || n % (6 * k - 1) == 0) return false;
return true;
}
I made this algorithm using two facts:
n % k == 0
up to k <= Math.sqrt(n)
. This is true because for anything higher, factors merely "flip" ex. consider the case n = 15
, where 3 * 5
= 5 * 3
, and 5
> Math.sqrt(15)
. There is no need for this overlap of checking both 15 % 3 == 0
and 15 % 5 == 0
, when we could just check one of these expressions.2
and 3
) can be expressed in the form (6 * k) + 1
or (6 * k) - 1
, because any positive integer can be expressed in the form (6 * k) + n
, where n = -1, 0, 1, 2, 3, or 4
and k
is an integer <= 0
, and the cases where n = 0, 2, 3, and 4
are all reducible.Therefore, n
is prime if it is not divisible by 2
, 3
, or some integer of the form 6k ± 1 <= Math.sqrt(n)
. Hence the above algorithm.
--
Wikipedia article on testing for primality
--
Edit: Thought I might as well post my full solution (*I did not use isPrime()
, and my solution is nearly identical to the top answer, but I thought I should answer the actual question):
public class Euler3 {
public static void main(String[] args) {
long[] nums = {13195, 600851475143L};
for (num : nums)
System.out.println("Largest prime factor of " + num + ": " + lpf(num));
}
private static lpf(long n) {
long largestPrimeFactor = 1;
long maxPossibleFactor = n / 2;
for (long i = 2; i <= maxPossibleFactor; i++)
if (n % i == 0) {
n /= i;
largestPrimeFactor = i;
i--;
}
return largestPrimeFactor;
}
}