nzakas/computer-science-in-javascript — Issue #5: Exponentiation by squaring
Author: Yaffle
Created: 2011-10-26 09:45:14+00:00
State: open

// http://en.wikipedia.org/wiki/Exponentiation_by_squaring
// n, k - integers, > 0
function pow(n, k) {
var b = 1;
while (k) {
if (k % 2) {
k--;
b *= n;
} else {
k /= 2;
n *= n;
}
}
return b;
}