-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathakpower.cpp
More file actions
43 lines (42 loc) · 889 Bytes
/
akpower.cpp
File metadata and controls
43 lines (42 loc) · 889 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// ===========================================================
// akpower.cpp
// Computes x to the non-negative integer power p using
// Al-Kashi's algorithm
// ===========================================================
#include <cassert>
using namespace std;
double akpower(double x, int p)
{
int sign = 1;
if(p < 0)
{
p = -p; // make power positive
sign = -1; // but remember it's supposed to be neg
}
int n = p;
double xn = x;
double result = 1.0;
// Invariant established: pow(x, p) = result * pow(xn, n)
while(1 <= n)
{
if( n%2 == 0)
{
n = n/2;
xn = xn * xn;
// pow(xn, n) has not changed
}
else
{
n = n - 1;
result = result * xn;
// result * pow(xn, n) has not changed
}
// Invariant: pow(x, p) = result * pow(xn, n)
}
// pow(x, p) = result * pow(xn, 0)
if(sign == -1)
{
result = 1.0/result;
}
return result;
}