Skip to content

Commit cbf5084

Browse files
PudottaPomminButt4cak3
authored andcommitted
Added implementation for euclidean algorithm in PHP (#430)
1 parent c907ebd commit cbf5084

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
function euclid_sub(int $a, int $b): int
5+
{
6+
$a = abs($a);
7+
$b = abs($b);
8+
9+
while ($a !== $b) {
10+
if ($a > $b) {
11+
$a = $a - $b;
12+
} else {
13+
$b = $b - $a;
14+
}
15+
}
16+
17+
return $a;
18+
}
19+
20+
function euclid_mod(int $a, int $b): int
21+
{
22+
$a = abs($a);
23+
$b = abs($b);
24+
25+
while ($b !== 0) {
26+
list($b, $a) = [$a % $b, $b];
27+
}
28+
29+
return $a;
30+
}
31+
32+
printf('Euclidean mod: %s', euclid_mod(64 * 67, 64 * 81));
33+
echo PHP_EOL;
34+
printf('Euclidean sub: %s', euclid_sub(128 * 12, 128 * 77));
35+
echo PHP_EOL;

contents/euclidean_algorithm/euclidean_algorithm.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two
4141
[import:13-24, lang="nim"](code/nim/euclid_algorithm.nim)
4242
{% sample lang="f90" %}
4343
[import:1-19, lang="fortran"](code/fortran/euclidean.f90)
44+
{% sample lang="php" %}
45+
[import:4-18, lang="php"](code/php/euclidean.php)
4446
{% sample lang="factor" %}
4547
[import:1-13, lang="factor"](code/factor/euclid.factor)
4648
{% sample lang="ws" %}
@@ -102,6 +104,8 @@ Modern implementations, though, often use the modulus operator (%) like so
102104
[import:1-11, lang="nim"](code/nim/euclid_algorithm.nim)
103105
{% sample lang="f90" %}
104106
[import:21-34, lang="fortran"](code/fortran/euclidean.f90)
107+
{% sample lang="php" %}
108+
[import:20-30, lang="php"](code/php/euclidean.php)
105109
{% sample lang="factor" %}
106110
[import:15-25, lang="factor"](code/factor/euclid.factor)
107111
{% sample lang="ws" %}
@@ -168,6 +172,8 @@ The Euclidean Algorithm is truly fundamental to many other algorithms throughout
168172
[import, lang="nim" %](code/nim/euclid_algorithm.nim)
169173
{% sample lang="f90" %}
170174
[import, lang="fortran"](code/fortran/euclidean.f90)
175+
{% sample lang="php" %}
176+
[import, lang="php"](code/php/euclidean.php)
171177
{% sample lang="factor" %}
172178
[import, lang="factor"](code/factor/euclid.factor)
173179
{% sample lang="ws" %}

0 commit comments

Comments
 (0)