Created
August 12, 2008 02:36
-
-
Save ishikawa/4992 to your computer and use it in GitHub Desktop.
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
| """ | |
| Fast Exponentiation | |
| http://www2.toki.or.id/book/AlgDesignManual/BOOK/BOOK2/NODE54.HTM#SECTION02361000000000000000 | |
| """ | |
| import math | |
| def slow_pow(a, n): | |
| x = 1 | |
| for i in xrange(n): | |
| x *= a | |
| return x | |
| def fast_pow(a, n): | |
| if n == 0: | |
| return 1 | |
| x = fast_pow(a, n/2) | |
| if n & 1 == 1: | |
| return a * x * x | |
| else: | |
| return x * x | |
| assert fast_pow(2, 0) == slow_pow(2, 0) == math.pow(2, 0) | |
| assert fast_pow(5, 5) == slow_pow(5, 5) == math.pow(5, 5) | |
| assert fast_pow(2, 32) == slow_pow(4, 16) == math.pow(16, 8) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment