Skip to content

Instantly share code, notes, and snippets.

@svdamani
Last active April 17, 2020 10:44
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save svdamani/1ccde0ad21686513cd0f to your computer and use it in GitHub Desktop.
Save svdamani/1ccde0ad21686513cd0f to your computer and use it in GitHub Desktop.
Fast Power calculation in Python
def power(base, exp):
""" Fast power calculation using repeated squaring """
if exp < 0:
return 1 / power(base, -exp)
ans = 1
while exp:
if exp & 1:
ans *= base
exp >>= 1
base *= base
return ans
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment