가능한 중복 : 나는 알고
The most efficient way to implement an integer based power function pow(int, int)양의 정수를 찾는 가장 빠른 알고리즘은 무엇입니까?
유일한 두 가지 방법,
루프 단일 : 매우 느린
재 작성 재귀 적으로 계산하다.
이 두 알고리즘보다 빠른 알고리즘이 있습니까? 모든 bitwise 기술을 환영합니다. 고맙습니다. 두 알고리즘
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;
}
}
@ 존 Zwinck : 고마워요. 3 번 검색했지만 해당 스레드를 찾을 수 없습니다. – Chan
가장 빠른 알고리즘은 거의 항상 미리 계산 된 테이블 조회입니다 .-) – paxdiablo
두 번째 재귀 호출은이 recurPow (a *, (e-1)/2) * a와 같아야합니다. 그것을 = 2, e = 5에서 시험하십시오. –