Use exponentiation by squaring instead of n-times multiplications in power() (#385)
This commit is contained in:
parent
ea43a61094
commit
a9557fe53d
|
@ -19,10 +19,19 @@ static cell power(AMX *amx, cell *params)
|
||||||
/* power(value, exponent);
|
/* power(value, exponent);
|
||||||
* params[1] = value
|
* params[1] = value
|
||||||
* params[2] = exponent
|
* params[2] = exponent
|
||||||
|
* Exponentiation by squaring
|
||||||
*/
|
*/
|
||||||
cell result = 1;
|
cell result = 1;
|
||||||
while (params[2]-- > 0)
|
cell value = params[1];
|
||||||
result *= params[1];
|
cell exp = params[2];
|
||||||
|
while (exp > 0) {
|
||||||
|
if (exp & 1) {
|
||||||
|
result *= value;
|
||||||
|
} /* if */
|
||||||
|
value *= value;
|
||||||
|
exp >>= 1;
|
||||||
|
} /* while */
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user