finding a^b^c^… mod m

前端 未结 6 1774
慢半拍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:37

    Modular Exponentiation is a correct way to solve this problem, here's a little bit of hint:

    To find abcd % m You have to start with calculating a % m, then ab % m, then abc % m and then abcd % m ... (you get the idea)

    To find ab % m, you basically need two ideas: [Let B=floor(b/2)]

  • ab = (aB)2 if b is even OR ab = (aB)2*a if b is odd.
  • (X*Y)%m = ((X%m) * (Y%m)) % m
    (% = mod)

    Therefore,
    if b is even
    ab % m = (aB % m)2 % m
    or if b is odd
    ab % m = (((aB % m)2) * (a % m)) % m

    So if you knew the value of aB, you can calculate this value.

    To find aB, apply similar approach, dividing B until you reach 1.

    e.g. To calculate 1613 % 11:

    1613 % 11 = (16 % 11)13 % 11 = 513 % 11 = (56 % 11) * (56 % 11) * (5 % 11) <---- (I)

    To find 56 % 11:
    56 % 11 = ((53 % 11) * (53 % 11)) % 11 <----(II)
    To find 53%11:
    53 % 11 = ((51 % 11) * (51 % 11) * (5 % 11)) % 11
    = (((5 * 5) % 11) * 5) % 11 = ((25 % 11) * 5) % 11 = (3 * 5) % 11 = 15 % 11 = 4
    Plugging this value to (II) gives
    56 % 11 = (((4 * 4) % 11) * 5) % 11 = ((16 % 11) * 5) % 11 = (5 * 5) % 11 = 25 % 11 = 3
    Plugging this value to (I) gives
    513 % 11 = ((3 % 11) * (3 % 11) * 5) % 11 = ((9 % 11) * 5) % 11 = 45 % 11 = 4

    This way 513 % 11 = 4
    With this you can calculate anything of form a513 % 11 and so on...

提交回复
热议问题