Num is unlikely to overflow, but you routinely compare it to Primes[Test] * Primes[Test], which seems like a possible candidate for overflow. I would check to see if that's your problem. Cast to...