English 中文(简体)
我正在寻找一个计算一些力量的算法。 (x^y), x and y are integers . 它必须是复杂的O(log [n])
原标题: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]))

目前,我的最佳努力导致奥洛(log2)的复杂性:

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 :)

最佳回答

在日志中实施这一行动的想法是使用以下(专题)等值(如第2号表示的分类):

x^0 = 1

x^n = (x n/2)2,条件是:% 2 = 页: 1

iii 页: 1

根据:

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;
        }
    }
}

这种执行将产生奥[log(n)]的复杂性,因为每次再入侵中的投入(变量N)都减半。

问题回答

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





相关问题
How to add/merge several Big O s into one

If I have an algorithm which is comprised of (let s say) three sub-algorithms, all with different O() characteristics, e.g.: algorithm A: O(n) algorithm B: O(log(n)) algorithm C: O(n log(n)) How do ...

Grokking Timsort

There s a (relatively) new sort on the block called Timsort. It s been used as Python s list.sort, and is now going to be the new Array.sort in Java 7. There s some documentation and a tiny Wikipedia ...

Manually implementing high performance algorithms in .NET

As a learning experience I recently tried implementing Quicksort with 3 way partitioning in C#. Apart from needing to add an extra range check on the left/right variables before the recursive call, ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Enumerating All Minimal Directed Cycles Of A Directed Graph

I have a directed graph and my problem is to enumerate all the minimal (cycles that cannot be constructed as the union of other cycles) directed cycles of this graph. This is different from what the ...

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...

热门标签