Merge pull request #33 from juan88/add-fast-exponentiation

Add fast exponentiation to math algorithms
This commit is contained in:
Brandon Johnson 2020-11-04 22:28:48 -07:00 committed by GitHub
commit 1ce43c932d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 35 additions and 0 deletions

View File

@ -12,6 +12,7 @@
- [Check Prime](https://github.com/TheAlgorithms/PHP/blob/master/Maths/CheckPrime.php)
- [Factorial](https://github.com/TheAlgorithms/PHP/blob/master/Maths/Factorial.php)
- [Perfect Square](https://github.com/TheAlgorithms/PHP/blob/master/Maths/PerfectSquare.php)
- [Fast Exponentiation](https://github.com/TheAlgorithms/PHP/blob/master/Maths/FastExponentiation.php)
## Searching

View File

@ -0,0 +1,24 @@
<?php
/**
* This functions computes an exponent by doing repeated squares
*
* @param Integer $base the base
* @param Integer $exponent the exponent (ie the number of times that the base is multiplied by itself)
* @return Integer
*/
function fastExponentiation(int $base, int $exponent)
{
if ($exponent == 0) {
return 1;
}
if ($exponent == 1) {
return $base;
}
if ($exponent % 2 == 0) {
return fastExponentiation($base*$base, $exponent/2);
} else {
return $base * fastExponentiation($base*$base, ($exponent-1)/2);
}
}

View File

@ -11,6 +11,7 @@ require_once __DIR__ . '/../Maths/CheckPrime.php';
require_once __DIR__ . '/../Maths/AbsoluteMax.php';
require_once __DIR__ . '/../Maths/AbsoluteMin.php';
require_once __DIR__ . '/../Maths/PerfectSquare.php';
require_once __DIR__ . '/../Maths/FastExponentiation.php';
class MathTest extends TestCase
{
@ -56,4 +57,13 @@ class MathTest extends TestCase
assertFalse(is_perfect_square(2));
assertTrue(is_perfect_square(225));
}
public function testFastExponentiation()
{
assertEquals(fastExponentiation(10, 0), 1);
assertEquals(fastExponentiation(10, 1), 10);
assertEquals(fastExponentiation(10, 2), 100);
assertEquals(fastExponentiation(10, 3), 1000);
assertEquals(fastExponentiation(20, 5), 3200000);
}
}