finding a^b^c^… mod m

前端 未结 6 1810
慢半拍i
慢半拍i 2020-11-29 23:53

I would like to calculate:

abcd... mod m

Do you know any efficient way since this number

6条回答
  •  被撕碎了的回忆
    2020-11-30 00:26

    1. Since for any relationship a=x^y, the relationship is invariant with respect to the numeric base you are using (base 2, base 6, base 16, etc).

    2. Since the mod N operation is equivalent to extracting the least significant digit (LSD) in base N

    3. Since the LSD of the result A in base N can only be affected by the LSD of X in base N, and not digits in higher places. (e.g. 34*56 = 30*50+30*6+50*4+4*5 = 10*(3+50+3*6+5*4)+4*6)

    Therefore, from LSD(A)=LSD(X^Y) we can deduce

    LSD(A)=LSD(LSD(X)^Y)
    

    Therefore

    A mod N = ((X mod N) ^ Y) mod N
    

    and

    (X ^ Y) mod N = ((X mod N) ^ Y) mod N)
    

    Therefore you can do the mod before each power step, which keeps your result in the range of integers.


    This assumes a is not negative, and for any x^y, a^y < MAXINT


    This answer answers the wrong question. (alex)

提交回复
热议问题