I am looking for an algorithm that calculates the

2019-07-17 07:55发布

问题:

Currently, my best effort has resulted in complexity O(log[n]^2):

int power(x,n)
{
  int mult=1, temp=x, i=1, j=1;
  while (n>1)
  {
    mult=mult*x;
    x=temp;
    for (i=1;i<=log[n];i++)
    {
      x=x*x;
      j=j*2;
    }
    n=n-j;
    i=1;
    j=1;
  }
  if (n==1)
    return (mult*temp);
  return (mult);
}

P.S Thank you funkymushroom for helping me with my bad English :)

回答1:

The idea behind implementing this operation in logarithmic time is to use the following (mathematical) equivalences (here n/2 denotes integer division):

x^0 = 1

x^n = (xn/2)2, if n % 2 == 0

x^n = x*(xn/2)2, if n % 2 == 1

This can easily be implemented recursively according to:

int power(int x, int n) {
    if (n == 0) {
        return 1;
    } else {
        int r = power(x, n / 2);
        if (n % 2 == 0) {
            return r * r;
        } else {
            return x * r * r;
        }
    }
}

An implementation such as this will yield a O[log(n)] complexity since the input (the variable n) is halved in each step of the recursion.



回答2:

What you need is to use repeated squaring. Check this out