Skip to content

Commit a9e823d

Browse files
authored
Merge pull request #141 from afonsocarlos/master
Add Greatest Common Divisor
2 parents 427faf7 + 7bb7414 commit a9e823d

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
* [Fastexponentiation](./Maths/FastExponentiation.php)
3636
* [Fibonacci](./Maths/Fibonacci.php)
3737
* [Fibonacci2](./Maths/Fibonacci2.php)
38+
* [Greatestcommondivisor](./Maths/GreatestCommonDivisor.php)
3839
* [Mean](./Maths/Mean.php)
3940
* [Median](./Maths/Median.php)
4041
* [Mode](./Maths/Mode.php)

Maths/GreatestCommonDivisor.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php
2+
3+
/**
4+
* This function finds the greatest common division using Euclidean algorithm
5+
* example: gcd(30, 24) => 6
6+
* @param int $a
7+
* @param int $b
8+
* @return int
9+
*/
10+
function gcd(int $a, int $b): int
11+
{
12+
if ($b == 0) {
13+
return $a;
14+
}
15+
return gcd($b, $a % $b);
16+
}

tests/Maths/MathsTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
require_once __DIR__ . '/../../Maths/FastExponentiation.php';
1313
require_once __DIR__ . '/../../Maths/Fibonacci.php';
1414
require_once __DIR__ . '/../../Maths/Fibonacci2.php';
15+
require_once __DIR__ . '/../../Maths/GreatestCommonDivisor.php';
1516
require_once __DIR__ . '/../../Maths/NeonNumber.php';
1617
require_once __DIR__ . '/../../Maths/PerfectSquare.php';
1718
require_once __DIR__ . '/../../Maths/Mean.php';
@@ -143,4 +144,14 @@ public function testMode()
143144
$this->assertEquals([1, 2, 3, 4, 5], mode(1, 2, 3, 4, 5));
144145
$this->assertEquals([2, 3, 4], mode(2, 2, 3, 3, 4, 4));
145146
}
147+
148+
public function testGreatestCommonDivisor()
149+
{
150+
$this->assertEquals(8, gcd(24, 16));
151+
$this->assertEquals(5, gcd(10, 5));
152+
$this->assertEquals(25, gcd(100, 75));
153+
$this->assertEquals(6, gcd(12, 18));
154+
$this->assertEquals(5, gcd(10, 15));
155+
$this->assertEquals(3, gcd(9, 12));
156+
}
146157
}

0 commit comments

Comments
 (0)