From a9557fe53d4f0d0518b2333533e27907a84db3b4 Mon Sep 17 00:00:00 2001 From: Alexander Petrov Date: Sat, 27 Aug 2016 18:12:02 +1000 Subject: [PATCH] Use exponentiation by squaring instead of n-times multiplications in power() (#385) --- amxmodx/power.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/amxmodx/power.cpp b/amxmodx/power.cpp index 0dfb2431..74f6f2b8 100755 --- a/amxmodx/power.cpp +++ b/amxmodx/power.cpp @@ -19,10 +19,19 @@ static cell power(AMX *amx, cell *params) /* power(value, exponent); * params[1] = value * params[2] = exponent + * Exponentiation by squaring */ cell result = 1; - while (params[2]-- > 0) - result *= params[1]; + cell value = params[1]; + cell exp = params[2]; + while (exp > 0) { + if (exp & 1) { + result *= value; + } /* if */ + value *= value; + exp >>= 1; + } /* while */ + return result; }