HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Speeding up my implementation of Project Euler #3

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
speedingimplementationprojecteuler

Problem

Project Euler problem 3 asks for the largest prime factor of 600851475143.

I have gone from 96 lines to 17 lines taking hits at this one. This is what I am left with after all of that effort:

public class IntegerFactoriseFive {

    public static void main(String[] args)
    {
        long n = 600851475143L;
        for (long i = 2; i <= n; i++)
        {
            if (n % i==0)
            {
                System.out.println(i);
                n = n / i;
                i = 2;
            }
        }
    }
}


Is there any way to make it faster?

I'm not suggesting that it isn't quick enough already, but for the sake of it and for improving the way I tackle problems in the future. My other solutions were taking forever. I was using recursion, and I even only iterated up to the square root of the numbers I was checking (from early school maths I know to only check up to the square root, it is a lot quicker), but it was still to slow. In the end, iterating by one and dividing this huge number was the wrong way to go about it, so instead, I figured that dividing the number as much as possible was the only way I could do it in any good time.

Please offer suggestions. As you can see by the class name, it is my fifth official solution for it that is the quickest of the ones I came up with.

Solution

By inspection, n has no even factors. You only need to try odd factors.

Whenever you find an i that is a divisor of n, you should factor out all powers of i. There is also no need for i to start from scratch — your hunt for divisors should proceed monotonically upward.

Your search can end when i reaches or surpasses the square root of n. At that point, n is the answer to the challenge.

(A reasonable algorithm should obtain the answer within milliseconds.)

Context

StackExchange Code Review Q#44300, answer score: 8

Revisions (0)

No revisions yet.