Skip to content

Instantly share code, notes, and snippets.

@onahirniak
Forked from svdamani/pow.py
Created January 13, 2019 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onahirniak/fddbe9ec036e3450bcab12b3d9d955fc to your computer and use it in GitHub Desktop.
Save onahirniak/fddbe9ec036e3450bcab12b3d9d955fc 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