mathexponentiationmodulo

How to compute a^b^c mod p?


I am trying to compute a^b^c mod p for some positive integers a,b,c,p. One possible (and obvious) way is to use fast modular exponentiation which will run in O(log(b^c))=clog(b). While I don't mind the efficiency here, the obvious downfall of this method is that you need an explicit binary representation of b^c which in itself is already exponential.

So the question for me is, if I can not represent b^c as a binary representation, is there a way I can compute a^b^c mod p from the binary representations of a,b, and c?


Solution

  • (a^b^c) mod p = (((a^b) mod p)^c) mod p
    

    So you can do

    modpow(modpow(a,b,p),c,p);
    

    Where all operands results and subresults are normal ints. As modpow you can use power by squaring in modulo p like here:

    beware those are a bit optimized taking advantage of the properties of specific selected p so you need to change lines like

    if (DWORD(d)>=DWORD(p)) d-=p;
    

    into

    d%=p;
    

    [Example]

    (2^3^5) % 6 = 
    (8  ^5) % 6 =
      32768 % 6 = 2
    
    (((2^3)%6)^5) % 6 = 
    ((   8 %6)^5) % 6 = 
    (    2    ^5) % 6 =
        32        % 6 = 2