Last active
April 17, 2020 10:44
-
-
Save svdamani/1ccde0ad21686513cd0f to your computer and use it in GitHub Desktop.
Fast Power calculation in Python
This file contains hidden or 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