1
\$\begingroup\$

I could not think of any better way to raise to power, except this, but how do I refactor it? I should only use while loop, not for loop, not x**y.

I shall not use pow(x,y)

result = 1
base = 3
counter = 1
degree = 4
while counter <= degree:
        result = base * result
        counter += 1
        print("counter %d and the result %d" %(counter, result))
print("result is ", result)
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Is this a programming challenge? If it is could you give us the formal requirements? Also do you want a review on the speed? \$\endgroup\$ Commented Apr 29, 2016 at 7:56
  • 1
    \$\begingroup\$ "Refactoring" has a very specific meaning. You shouldn't use the term as a synonym for "improve". \$\endgroup\$ Commented Apr 29, 2016 at 9:17
  • \$\begingroup\$ You can see some ways of doing what you want here: programminglogic.com/fast-exponentiation-algorithms \$\endgroup\$ Commented Apr 29, 2016 at 10:44

1 Answer 1

3
\$\begingroup\$

Your algorithm is \$O(n)\$ where \$n = \text{degree}\$. This means the performance of your code is quite poor. You can make an \$O(\log(n))\$ algorithm by using binary operators on the exponent.

For an explanation of this algorithm, you:

  • Have the exponent in a form where you can manipulate it's binary.
  • Whilst the exponent isn't empty:

    • If the last (smallest) index of the exponent is 1, times result by the base.
    • Remove the last index of the exponent.
    • Multiply the base by it's self.

Which results in:

def pow(base, exp):
    result = 1
    while exp:
        if exp & 1:
            result *= base
        exp >>= 1
        base *= base
    return result
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.