2

For example, if A = 864927518, B = 1462579282 ,M = 193773611, how to compute (A^B)%M?

Is there a simple way?

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
Ren
  • 2,852
  • 2
  • 23
  • 45
  • 2
    possible duplicate of [Calculating pow(a,b) mod n](http://stackoverflow.com/questions/8496182/calculating-powa-b-mod-n) – phuclv Sep 22 '15 at 09:20
  • 2
    [Modular exponentiation implementation in Python 3](http://stackoverflow.com/q/18804958/995714), [How did Python implement the built-in function pow()?](http://stackoverflow.com/a/10539256/995714) – phuclv Sep 22 '15 at 09:23

3 Answers3

7

Yes: use modular exponentiation. Python's built in pow function allows you to do this with its optional third argument:

>>> pow(A, B, M)
2767533
Alex Riley
  • 169,130
  • 45
  • 262
  • 238
2
3>> pow(864927518, 1462579282, 193773611)
2767533
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

I shall blithely assume that you are using ^ as the exponentiation operator here (rather than as XOR). You can either use the built-in pow or you can code your own:

import math

def expmod(i, j, m):
  """Compute (i ** j) % m"""

  acc = 1
  mask = 2 ** int(math.ceil(math.log(j, 2)))
  while mask > 0:
    acc = acc * acc
    if mask & j:
      acc = acc * i
      j = j ^ mask
    mask = mask // 2
    acc = acc % m

  return acc
Vatine
  • 20,782
  • 4
  • 54
  • 70