可能重复:
The most efficient way to implement an integer based power function pow(int, int)寻找正整数的力量最快的算法是什么?
只有两个方法,我知道的是,
单一的for循环:极其缓慢
重写递归计算。
我不知道是否有比这两个更快的算法?任何按位技术都是受欢迎的。谢谢。
两个算法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;
}
}
@John Zwinck:非常感谢。我搜索了3次,但无法找到该线程。 – Chan 2011-04-24 23:42:56
最快的算法几乎总是一个预先计算的表查找:-) – paxdiablo 2011-04-25 00:01:31
我相信第二次递归调用应该是这样'recurPow(a * a,(e - 1)/ 2)* a'。在a = 2上测试它,e = 5 – 2013-03-05 22:08:30