2011-04-24 46 views
2

可能重复:
The most efficient way to implement an integer based power function pow(int, int)寻找正整数的力量最快的算法是什么?

只有两个方法,我知道的是,

  1. 单一的for循环:极其缓慢

  2. 重写enter image description here递归计算。

我不知道是否有比这两个更快的算法?任何按位技术都是受欢迎的。谢谢。

两个算法C#演示:

 class Math { 
     static public Int64 recurPow(Int64 a, Int64 e) { 
      if (e == 0) 
       return 1; 
      if (e == 1) 
       return a; 
      if ((e % 2) == 0) 
       return recurPow(a * a, e/2); 
      else 
       return recurPow(a * a, (e - 1)/2); 
     } 

     static public Int64 iterPow(Int64 a, Int64 e) { 
      Int64 result = a; 
      for (Int64 i = 1; i < e; ++i) 
       result *= a; 
      return result; 
     } 
    } 
+0

@John Zwinck:非常感谢。我搜索了3次,但无法找到该线程。 – Chan 2011-04-24 23:42:56

+0

最快的算法几乎总是一个预先计算的表查找:-) – paxdiablo 2011-04-25 00:01:31

+0

我相信第二次递归调用应该是这样'recurPow(a * a,(e - 1)/ 2)* a'。在a = 2上测试它,e = 5 – 2013-03-05 22:08:30

回答

2

的最优算法是NP完全问题,见http://en.wikipedia.org/wiki/Addition-chain_exponentiation

该页面还链接了一些启发式算法,给出不错的答案,你可能想要其中之一。

你也在做comp3212吗?

+0

谢谢。我不是在那个班上,只是在阅读数学书时才了解它。 – Chan 2011-04-24 23:48:09

+0

那么我们有这个问题分配给我们。讲师有一种“意外”分配无法解决的问题的习惯。 – riri 2011-04-24 23:57:16

相关问题