Skip to content

Instantly share code, notes, and snippets.

@ChrisLeNeve
Created October 1, 2019 12:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisLeNeve/80ff273c222e22c14e9671c58461f9e2 to your computer and use it in GitHub Desktop.
Save ChrisLeNeve/80ff273c222e22c14e9671c58461f9e2 to your computer and use it in GitHub Desktop.
Find largest prime factor
import java.util.HashMap;
import java.util.Map;
class Scratch {
public static void main(String[] args) {
long number = 600851475143L;
// long number = 13195;
long result = findLargestPrimeFactor(number);
System.out.println(result);
}
private static long findLargestPrimeFactor(long number) {
long squareRoot = (long)Math.ceil(Math.sqrt(number));
Map<Long, Boolean> eratosthenesReturn = eratosthenesSieve(squareRoot);
long max = Integer.MIN_VALUE;
for (long l : eratosthenesReturn.keySet()) {
if (l > max && !eratosthenesReturn.get(l) && (number % l == 0))
max = l;
}
return max;
}
private static Map<Long, Boolean> eratosthenesSieve(long max) {
// boolean = is composite. false if prime
Map<Long, Boolean> sieve = new HashMap<>();
// sieve.put(2L, false);
// sieve.put(3L, false);
for (long i = 2; i <= max; i++) {
sieve.put(i, false);
}
for (long i = 2; i < max; i++) {
if (!sieve.get(i)) {
for (long j = i * 2; j < max; j += i) {
sieve.put(j, true);
}
}
}
return sieve;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment