org.psjava.algo.math.numbertheory.PrimalityTesterByPreparedPrimeDivision Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of psjava Show documentation
Show all versions of psjava Show documentation
Problem Solving Library for Java
package org.psjava.algo.math.numbertheory;
import org.psjava.ds.array.Array;
/**
* Almost same with {@link PrimalityTesterByDivision}. But if there are prepared primes, we can do division-test only for primes.
*
* Then, the time is almost 10 times faster than {@link PrimalityTesterByDivision}.
*
* Here, we uses prime number sieve to get prime number list.
*/
public class PrimalityTesterByPreparedPrimeDivision {
public static PrimalityTester getInstance(long max, PrimeNumberSieve sieve) {
final Array primes = sieve.calcList((int) Math.sqrt(max) + 1);
return new PrimalityTester() {
@Override
public boolean isPrime(long v) {
if (v <= 1)
return false;
for (long p : primes) {
if (p * p > v)
break;
if (v % p == 0)
return false;
}
return true;
}
};
}
private PrimalityTesterByPreparedPrimeDivision() {
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy