Fast way to manually mod a number

Posted by Nikolai Mushegian on Stack Overflow See other posts from Stack Overflow or by Nikolai Mushegian
Published on 2009-06-12T17:32:13Z Indexed on 2010/05/09 21:08 UTC
Read the original article Hit count: 238

Filed under:
|
|

I need to be able to calculate (a^b) % c for very large values of a and b (which individually are pushing limit and which cause overflow errors when you try to calculate a^b). For small enough numbers, using the identity (a^b)%c = (a%c)^b%c works, but if c is too large this doesn't really help. I wrote a loop to do the mod operation manually, one a at a time:

private static long no_Overflow_Mod(ulong num_base, ulong num_exponent, ulong mod) 
    {
        long answer = 1;
        for (int x = 0; x < num_exponent; x++)
        {
            answer = (answer * num_base) % mod;
        }
        return answer;
    }

but this takes a very long time. Is there any simple and fast way to do this operation without actually having to take a to the power of b AND without using time-consuming loops? If all else fails, I can make a bool array to represent a huge data type and figure out how to do this with bitwise operators, but there has to be a better way.

© Stack Overflow or respective owner

Related posts about modulus

Related posts about c#