Skip to content

Instantly share code, notes, and snippets.

@VictoriqueMoe
Created October 25, 2024 12:09
Show Gist options
  • Save VictoriqueMoe/5ef160374784bb4f83b941c820d39e42 to your computer and use it in GitHub Desktop.
Save VictoriqueMoe/5ef160374784bb4f83b941c820d39e42 to your computer and use it in GitHub Desktop.
java prime
package org.example;
import com.google.common.base.Stopwatch;
import java.math.BigInteger;
public class PrimeChecker {
public static boolean checkPrime(final BigInteger given) {
if (
given.equals(BigInteger.ONE)
|| given.compareTo(BigInteger.valueOf(4)) < 0
|| given.mod(BigInteger.TWO).equals(BigInteger.ZERO)
) {
return false;
}
final var max = given.sqrt().longValue();
for (long i = 2; i < max; i += 2) {
if (given.mod(BigInteger.valueOf(i + 1)).equals(BigInteger.ZERO)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
final var stopwatchTTotal = Stopwatch.createStarted();
BigInteger[] primesBeforeList = {
BigInteger.valueOf(60),
BigInteger.valueOf(6000000000L),
BigInteger.valueOf(60000000000L),
BigInteger.TWO.pow(32),
BigInteger.TWO.pow(40),
BigInteger.TWO.pow(44),
BigInteger.TWO.pow(48),
BigInteger.TWO.pow(56),
BigInteger.TWO.pow(64)
};
for (var primeBefore : primesBeforeList) {
final var checkingFor = primeBefore;
final var stopwatch = Stopwatch.createStarted();
primeBefore = primeBefore.mod(BigInteger.TWO).equals(BigInteger.ZERO) ? primeBefore.subtract(BigInteger.ONE) : primeBefore.subtract(BigInteger.TWO);
while (primeBefore.compareTo(BigInteger.ZERO) > 0 && !checkPrime(primeBefore)) {
primeBefore = primeBefore.subtract(BigInteger.TWO);
}
final var elapsed = stopwatch.stop();
if (primeBefore.compareTo(BigInteger.ZERO) > 0) {
System.out.printf("First prime before %s is %s in " + elapsed + " %n", checkingFor, primeBefore);
} else {
System.out.printf("No previous prime found in " + elapsed + " %n");
}
}
final var elapsed = stopwatchTTotal.stop();
System.out.printf("Total time elapsed: " + elapsed + " %n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment