Last active
March 30, 2016 18:02
-
-
Save shaunlgs/6391f818af6ba5e903ef to your computer and use it in GitHub Desktop.
LCM method (using GCD through Euclid) to find the smallest number that can be divided with number 1 to 20
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* function gcd() | |
* | |
* returns greatest common divisor | |
* between two numbers | |
* tested against gmp_gcd() | |
* credit: http://php.net/manual/en/function.gmp-gcd.php#86931 | |
*/ | |
function gcd($a, $b) | |
{ | |
if ($a == 0 || $b == 0) | |
return abs( max(abs($a), abs($b)) ); | |
$r = $a % $b; | |
return ($r != 0) ? | |
gcd($b, $r) : | |
abs($b); | |
} | |
function lcm($num1, $num2) | |
{ | |
$gcd = gcd($num1, $num2); | |
return ($num1 * $num2) / $gcd; | |
} | |
$number = 1; | |
$current = 1; | |
for($i=1; $i<20; $i++) | |
{ | |
$current = lcm($current, $number+1); | |
$number++; | |
} | |
echo $current; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment