Fixed bottleneck. It was in next_prime function where I was using unsigned int for i instead of long.