Self Power

Consider the problem of calculating power x n x^{n} where x x is any number, and n n is a positive integer. If you create your own power function, what is best possible complexity of the function?

O ( n ) O(n) O ( log n ) O(\log n) O ( n log n ) O(n\log n) O ( log log ( n ) ) O(\log\log (n))

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

2 solutions

Beakal Tiliksew
Apr 30, 2016

A recursive O ( n ) O(n) implementation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def power(x,y):
    if y==0:
        return 1
    elif y==1:
        return x
    else:
        if y % 2==0:
            return power(x, y//2)* power(x, y//2)
        else:
           return x*power(x, y//2)* power(x, y//2)

We can reduce it to O ( log ( n ) ) O(\log(n)) by calculating power(x, y//2) only once at each level.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def power(x,y):
    if y==0:
        return 1
    elif y==1:
        return x
    else:
        temp=power(x, y//2)
        if y % 2==0:
            return temp*temp
        else:
           return x*temp*temp

An alternative iterative implementation would be

1
2
3
4
5
6
int pow(int a, int p) {
    int ans = 1;
    for (; p; p >>= 1, a = a * a)
        if (p&1) ans = ans * a;
    return ans;
}

Christopher Boo - 5 years, 1 month ago
Rico Lee
May 6, 2016

Somehow I got this right. I do not do computer science at all, however, using mathematical knowledge 'n log x' is also log x^n. I guessed I started swapping the x and n around.

So, seeing as I only need one log...O(log n) is my answer. Wow.

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...