-
-
Save onahirniak/fddbe9ec036e3450bcab12b3d9d955fc to your computer and use it in GitHub Desktop.
Fast Power calculation in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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