I am looking for an algorithm that calculates the power of a number. (x^y), x and y are integers . It must be of complexity O(log[n]))

纵然是瞬间 提交于 2019-12-11 02:58:15

问题


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



来源:https://stackoverflow.com/questions/7988083/i-am-looking-for-an-algorithm-that-calculates-the-power-of-a-number-xy-x-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!