mirror of
https://github.com/TheAlgorithms/PHP.git
synced 2025-01-16 22:58:14 +01:00
Add Greatest Common Divisor
This commit is contained in:
parent
e4457ea9fa
commit
2553639335
16
Maths/GreatestCommonDivisor.php
Normal file
16
Maths/GreatestCommonDivisor.php
Normal file
@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This function finds the greatest common division using Euclidean algorithm
|
||||
* example: gcd(30, 24) => 6
|
||||
* @param int $a
|
||||
* @param int $b
|
||||
* @return int
|
||||
*/
|
||||
function gcd(int $a, int $b): int
|
||||
{
|
||||
if ($b == 0) {
|
||||
return $a;
|
||||
}
|
||||
return gcd($b, $a % $b);
|
||||
}
|
@ -12,6 +12,7 @@ require_once __DIR__ . '/../../Maths/Factorial.php';
|
||||
require_once __DIR__ . '/../../Maths/FastExponentiation.php';
|
||||
require_once __DIR__ . '/../../Maths/Fibonacci.php';
|
||||
require_once __DIR__ . '/../../Maths/Fibonacci2.php';
|
||||
require_once __DIR__ . '/../../Maths/GreatestCommonDivisor.php';
|
||||
require_once __DIR__ . '/../../Maths/NeonNumber.php';
|
||||
require_once __DIR__ . '/../../Maths/PerfectSquare.php';
|
||||
require_once __DIR__ . '/../../Maths/Mean.php';
|
||||
@ -143,4 +144,14 @@ class MathsTest extends TestCase
|
||||
$this->assertEquals([1, 2, 3, 4, 5], mode(1, 2, 3, 4, 5));
|
||||
$this->assertEquals([2, 3, 4], mode(2, 2, 3, 3, 4, 4));
|
||||
}
|
||||
|
||||
public function testGreatestCommonDivisor()
|
||||
{
|
||||
$this->assertEquals(8, gcd(24, 16));
|
||||
$this->assertEquals(5, gcd(10, 5));
|
||||
$this->assertEquals(25, gcd(100, 75));
|
||||
$this->assertEquals(6, gcd(12, 18));
|
||||
$this->assertEquals(5, gcd(10, 15));
|
||||
$this->assertEquals(3, gcd(9, 12));
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user