Much more efficient prime check algorithm