-
Notifications
You must be signed in to change notification settings - Fork 118
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #365 from tspeng/fast-power
Fast power
- Loading branch information
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
def fastpower(x, n): | ||
""" | ||
implement a fast power algorithm | ||
x : any float number, which works in python2 and 3 | ||
n : any integer including negative | ||
""" | ||
if(x == 0): | ||
return 0. | ||
|
||
if(n == 0): | ||
return 1.0 | ||
# when n < 0, convert it to positve by taking the reciprocal of x | ||
if(n < 0): | ||
x = 1 / x | ||
n = abs(n) | ||
|
||
if(n % 2 == 0): | ||
return fastpower(x, n // 2) ** 2 | ||
else: | ||
return fastpower(x, (n - 1) // 2) ** 2 * x | ||
|
||
if __name__ == "__main__": | ||
x = float(input("Please input the base: ")) | ||
n = int(input("Please input the power(int): ")) | ||
|
||
if(x == 0. and n == 0): | ||
print("0 to the power of 0 is undefined") | ||
else: | ||
print("{} to the power of {} is : {}".format(x, n, fastpower(x, n))) |