|
| 1 | +def getPower(base, exponent): |
| 2 | + return _getPower(base, exponent) if (exponent >= 0) else 1. / _getPower(base, exponent * -1); |
| 3 | + |
| 4 | +def _getPower(base, exponent): |
| 5 | + """ |
| 6 | + Given 2 numbers x and y, this function computes x raised to the power of y. |
| 7 | + this is a divide and conquer algorithm which means that this function does |
| 8 | + not multiply x times itself y times, it takes into consideration that if y is |
| 9 | + an even number then x^y = x^(y/2) * x^(y/2). If y is an odd number then |
| 10 | + x^y = x^((y-1) / 2) * x^((y-1) / 2) * x. This of course saves a lot of work. |
| 11 | + this algorithm runs in O(log y) instead of O(y) |
| 12 | + """ |
| 13 | + # The exponent is 0 so the answer is 1 |
| 14 | + if (exponent == 0): |
| 15 | + return 1; |
| 16 | + |
| 17 | + # The exponent is even so base ^ exponent = base ^ (exponent / 2) * base ^ (exponent / 2) |
| 18 | + if (exponent % 2 == 0): |
| 19 | + root = _getPower(base, exponent / 2); |
| 20 | + return root * root; |
| 21 | + |
| 22 | + # The exponent is not even so base ^ exponent = base ^ ((exponent - 1) / 2) * base ^ ((exponent - 1) / 2) |
| 23 | + semiRoot = _getPower(base, (exponent - 1) / 2); # Sorry for that silly name but could not find a better one :) |
| 24 | + return semiRoot * semiRoot * base; |
| 25 | + |
| 26 | +while(True): |
| 27 | + try: |
| 28 | + base = input("Enter the base: "); |
| 29 | + exponent = input("Enter the exponent: "); |
| 30 | + |
| 31 | + result = getPower(base, exponent); |
| 32 | + print("{0} ^ {1} = {2}".format(base, exponent, result)); |
| 33 | + break; |
| 34 | + |
| 35 | + except Exception as e: |
| 36 | + print("------------------------------------------------") |
| 37 | + print("Please Enter both a base and an integer exponent"); |
0 commit comments