Add Greatest Common Divisor

This commit is contained in:
Carlos Afonso 2023-10-22 21:35:08 +01:00
parent e4457ea9fa
commit 2553639335
2 changed files with 27 additions and 0 deletions

View 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);
}

View File

@ -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));
}
}