More efficient algorithm for mod function.