ugly nextprime code