# Project Euler Problem #3 in Java - Largest Prime Factor

I have solved the problem and it gives me the right output when the BigInteger has the smaller value, however it kept running for more than 20 minutes with the larger value without printing out an answer. So I'm thinking that there should be a faster algorithm for this program.

The problem states:

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

Main Method:

printPrimeFactors(new BigInteger("13195"));


Output:

29 13 7 5

BUILD SUCCESSFUL (total time: 0 seconds)

But when I change the value:

Main Method

printPrimeFactors(new BigInteger("600851475143"));


The program keeps running for a long time (more than 20 minutes), I didn't wait for an answer and stopped it.

Here is the rest of the program:

public static boolean isPrime(BigInteger n) {
if(n.compareTo(new BigInteger("2")) == -1) return false;
if(n.equals(new BigInteger("2")) || n.equals(new BigInteger("3"))) return true;
if(n.remainder(new BigInteger("2")).equals(BigInteger.ZERO) || n.remainder(new BigInteger("3")).equals(BigInteger.ZERO)) return false;

for(BigInteger i = new BigInteger("6"); i.compareTo(sqrtN) == 0 || i.compareTo(sqrtN) == -1; i = i.add(new BigInteger("6"))){
if(n.remainder(i.subtract(BigInteger.ONE)).equals(BigInteger.ZERO)) return false;
}
return true;
}

public static void printPrimeFactors(BigInteger number){

for(BigInteger i = BigInteger.ZERO.add(number);!i.equals(new BigInteger("1")); i = i.subtract(BigInteger.ONE)){
if(isPrime(i) && number.remainder(i).equals(BigInteger.ZERO)){
System.out.print(i + " ");
number = number.divide(i);
printPrimeFactors(number);
break;
}
}
}

public static BigInteger bigIntSqRootFloor(BigInteger x)
throws IllegalArgumentException {
if (x.compareTo(BigInteger.ZERO) < 0) {
throw new IllegalArgumentException("Negative argument.");
}

if (x .equals(BigInteger.ZERO) || x.equals(BigInteger.ONE)) {
return x;
}

BigInteger two = BigInteger.valueOf(2L);
BigInteger y;

for(y = x.divide(two);
y.compareTo(x.divide(y)) > 0;
return y;
}


First of all, you don't need a BigInteger. The target number fits in a long, use it.

The idea here, of course, is to find the largest prime factor, so given a number $N$, you should start checking primality starting from $\lfloor \sqrt{N} \rfloor$ "downwards." That way, the first prime factor you encounter is the largest one. You can do it like that:

private static final long TARGET_NUMBER = 600851475143L;

public void solve() {
long start = System.currentTimeMillis();
final long TARGET_NUMBER_SQRT = (long) Math.sqrt(TARGET_NUMBER);

for (long factor = TARGET_NUMBER_SQRT; factor > 1L; --factor) {
if (Utils.isPrime(factor) && (TARGET_NUMBER % factor == 0L)) {
System.out.println(factor);
break;
}
}
long end = System.currentTimeMillis();
System.out.println("Duration: " + (end - start) + " milliseconds.");
}


Above, isPrime is:

public static boolean isPrime(final long candidate) {
if (candidate < 2L) {
return false;
}

if (candidate % 2 == 0 && candidate != 2L) {
return false;
}

final long candidateSqrt = (long) Math.sqrt(candidate);

for (long f = 3L; f <= candidateSqrt; f += 2L) {
if (candidate % f == 0L) {
return false;
}
}

return true;
}


The performance figures are as follows:

6857
Duration: 303 milliseconds.

• I didn't realise that it fits in long until it was too late. However I've changed the i form zero to the square root of the number and removed the line where the recursion occurs. It worked like a charm. The duration was less than a second. What a difference! and Thanks for pointing out that I ONLY need the largest prime factor, I guess the answer was in the question the whole time. Commented Sep 14, 2016 at 7:09
• @Harout Sure. The answer to each and every PE question is an integer. Yet as far as I recall, you will need BigInteger in later questions. Commented Sep 14, 2016 at 7:13
• The largest prime factor may not be smaller than the square root. Consider 22 for example. Or 23 for that matter. Commented Sep 14, 2016 at 22:39

Counting downwards hurts the performance extremely as you are checking way more values than you have to (e.g. for this value you have to iterate only to the second largest prime number (1471) to know the largest prime number).

final long t0 = System.nanoTime();
final long factor = largestPrimeFactor(600851475143L);
final long t1 = System.nanoTime();
System.out.println(t1 - t0);
System.out.println(factor);


Results (significantly faster):

19071
6857


The code in largestPrimeFactors is a bit modified version of a normal primeFactor method (iterating only over values that are not a multiple of 2 or 3):

public static long largestPrimeFactor(
final long input) {
////
if (input < 2)
throw new IllegalArgumentException();

long n = input;
long last = 0;
for (; (n & 1) == 0; n >>= 1)
last = 2;
for (; n % 3 == 0; n /= 3)
last = 3;
for (long v = 5, add = 2, border = (long) Math.sqrt(n); v <= border; v += add, add ^= 6)
while (n % v == 0)
border = (long) Math.sqrt(n /= last = v);
return n == 1 ? last : n;
}
{"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 1, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "url": "https://codereview.stackexchange.com/questions/141296/project-euler-problem-3-in-java-largest-prime-factor", "fetch_time": 1718460778000000000, "content_mime_type": "text/html", "warc_filename": "crawl-data/CC-MAIN-2024-26/segments/1718198861594.22/warc/CC-MAIN-20240615124455-20240615154455-00323.warc.gz", "warc_record_offset": 149347067, "warc_record_length": 42206, "token_count": 1287, "char_count": 5092, "score": 3.546875, "int_score": 4, "crawl": "CC-MAIN-2024-26", "snapshot_type": "latest", "language": "en", "language_score": 0.4008045494556427, "file_path": "/sailhome/yjruan/project/latent-lm/data/processed/finemath-4plus/finemath-4plus/train-00052-of-00064.parquet"}