I think your problem is that you are using double instead of long (integer values), since doubles are stored only as approximations to the real number you might get rounding errors. See also this post Why is modulus operator not working for double in c#?
If you are dealing with larger values you will have to use a Structure with arbitrary size like BigInteger
.