Skip to main content
6 of 6
added 25 characters in body
Alnitak
  • 441
  • 2
  • 7

Here's my effort, which solves in ~240µs on an i7 iMac:

private long highest;

// checks if `f` is a factor of `n`,
// returning divided `n` accordingly
private long factorize(long n, long f) {
    if (n < f) return n;
    while (n % f == 0) {
        n /= f;
        if (f > highest) {
            highest = f;
        }
    }
    return n;
}

public long find(long n) {
    highest = 1;

    // check the two simplest cases
    n = factorize(n, 2);
    n = factorize(n, 3);

    // and then all numbers in the form 6x - 1 and 6x + 1
    if (n >= 5) {
        for (long i = 5; i * i <= n; i += 6) {
            n = factorize(n, i);
            n = factorize(n, i + 2);
        }
    }
    return (n == 1) ? highest : n;
}

This is a corrected version of @thepace's algorithm with special case tests for 2, 3, and then 6n - 1 and 6n + 1

Alnitak
  • 441
  • 2
  • 7