C# – long/large numbers and modulus in .NET


I'm currently writing a quick custom encoding method where I take a stamp a key with a number to verify that it is a valid key.

Basically I was taking whatever number that comes out of the encoding and multiplying it by a key.

I would then multiply those numbers to the deploy to the user/customer who purchases the key. I wanted to simply use (Code % Key == 0) to verify that the key is valid, but for large values the mod function does not seem to function as expected.

Number = 468721387;
Key = 12345678;
Code = Number * Key;

Using the numbers above:
Code % Key == 11418772

And for smaller numbers it would correctly return 0. Is there a reliable way to check divisibility for a long in .NET?


Ok, tell me if I'm special and missing something…

        long a = DateTime.Now.Ticks;
        long b = 12345;
        long c = a * b;
        long d = c % b;
        d == 10001 (Bad)


        long a = DateTime.Now.Ticks;
        long b = 12;
        long c = a * b;
        long d = c % b;
        d == 0 (Good)

What am I doing wrong?

Best Solution

As others have said, your problem is integer overflow. You can make this more obvious by checking "Check for arithmetic overflow/underflow" in the "Advanced Build Settings" dialog. When you do so, you'll get an OverflowException when you perform *DateTime.Now.Ticks * 12345*.

One simple solution is just to change "long" to "decimal" (or "double") in your code.

In .NET 4.0, there is a new BigInteger class.

Finally, you say you're "... writing a quick custom encoding method ...", so a simple homebrew solution may be satisfactory for your needs. However, if this is production code, you might consider more robust solutions involving cryptography or something from a third-party who specializes in software licensing.