Skip to content

Instantly share code, notes, and snippets.

@apangin
Last active July 2, 2019 22:04
Show Gist options
  • Save apangin/800e75bee6f8f72b76c721c27d5089e2 to your computer and use it in GitHub Desktop.
Save apangin/800e75bee6f8f72b76c721c27d5089e2 to your computer and use it in GitHub Desktop.
package bench;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
@State(Scope.Benchmark)
public class PrimeFactors {
// fast version
static int countPrimeFactorsSet(int n) {
Set<Integer> primeFactorSet = new HashSet<>();
while (n % 2 == 0) {
primeFactorSet.add(2);
n /= 2;
}
for (int i = 3; i <= Math.sqrt(n); i += 2) {
while (n % i == 0) {
primeFactorSet.add(i);
n /= i;
}
}
if (n > 2) {
primeFactorSet.add(n);
}
return primeFactorSet.size();
}
// slow version
static int countPrimeFactorsCounter(int n) {
int count = 0; // using simple int
if (n % 2 == 0) {
count ++; // only add on first division
n /= 2;
while (n % 2 == 0) {
n /= 2;
}
}
for (int i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) {
count++; // only add on first division
n /= i;
while (n % i == 0) {
n /= i;
}
}
}
if (n > 2) {
count++;
}
return count;
}
@Benchmark
public int counter() {
return countPrimeFactorsCounter(random());
}
@Benchmark
public int set() {
return countPrimeFactorsSet(random());
}
private int random() {
return ThreadLocalRandom.current().nextInt(10_000_000) + 1;
}
}
Benchmark Mode Cnt Score Error Units
PrimeFactors.counter thrpt 5 717,976 ± 7,232 ops/ms
PrimeFactors.set thrpt 5 1410,705 ± 15,894 ops/ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment