Skip to content

Instantly share code, notes, and snippets.

@aaani
Last active December 21, 2015 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaani/6303339 to your computer and use it in GitHub Desktop.
Save aaani/6303339 to your computer and use it in GitHub Desktop.
PHP implementation for 'Exponentiation by Squaring' method for finding power of a given number. This algorithm runs in O(log(P)) time where P is the power.
function findPower($base, $exponent){
if($exponent==0) return 1;
$output=$base;
$p=1;
while($p*2<$exponent){
$output*=$output;
$p+=$p;
}
return $output*findPower($base, $exponent-$p);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment