Advertisement
kerelius

modExp (Python)

Dec 10th, 2021
921
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.37 KB | None | 0 0
  1. # b^n (mod m)
  2. def modExp(b, n, m):
  3.     binary = format(n, "0b")
  4.     result = 1
  5.    
  6.     # Update b if it is more than or equal to m
  7.     b = b % m
  8.  
  9.     if (b == 0):
  10.         return 0
  11.  
  12.     binary = str(binary)[::-1]
  13.  
  14.     for i in range(len(binary)):
  15.         if (binary[i] == "1"):
  16.             result = (result * b) % m
  17.         b = (b * b) % m
  18.  
  19.     return result
  20.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement