speed up and factor out isPrime