Optimize primes implementation