Skip to content

Instantly share code, notes, and snippets.

@jinwoo1225
Created May 31, 2021 04:56
Show Gist options
  • Save jinwoo1225/09fe2cff6db9e2a6af9fa2e5a6c30b05 to your computer and use it in GitHub Desktop.
Save jinwoo1225/09fe2cff6db9e2a6af9fa2e5a6c30b05 to your computer and use it in GitHub Desktop.
def fast_pow(n: int, k: int, mod: int) -> int:
"""
faster power that uses Divide & Conquer
:param n: base
:param k: count
:param mod: modular
:return: powered n to k
"""
if n == 0:
raise ArithmeticError("n can't be 0")
if k == 0:
return 1
temp: int = fast_pow(n, k // 2, mod)
ret: int = (temp * temp) % mod
if k % 2:
ret = (ret * n) % mod
return ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment