Skip to content

Instantly share code, notes, and snippets.

@shaunlgs
Last active March 30, 2016 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaunlgs/6391f818af6ba5e903ef to your computer and use it in GitHub Desktop.
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
<?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