mirror of
https://github.com/TheAlgorithms/PHP.git
synced 2025-03-17 13:09:43 +01:00
Merge pull request #33 from juan88/add-fast-exponentiation
Add fast exponentiation to math algorithms
This commit is contained in:
commit
1ce43c932d
@ -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
|
||||
|
||||
|
24
Maths/FastExponentiation.php
Normal file
24
Maths/FastExponentiation.php
Normal 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);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user