Reputation: 621
My idea was something like this for finding the minimum number that is divisible from 1 to 12. The problem is, i have to use if condition all the way-long as the range of number increases. Is there any better way than this messy code.Sorry am a beginner from level 0.
<?php
for ($i = 1; $i <= 999999; $i++) {
$num = 12 * $i;
if ($num % 12 == 0) {
if ($num % 11 == 0) {
if ($num % 10 == 0) {
if ($num % 9 == 0) {
if ($num % 8 == 0) {
if ($num % 7 == 0) {
if ($num % 6 == 0) {
if ($num % 5 == 0) {
if ($num % 4 == 0) {
if ($num % 3 == 0) {
if ($num % 2 == 0) {
echo $num;
exit();
}
}
}
}
}
}
}
}
}
}
}
}
?>
Upvotes: 1
Views: 66
Reputation: 411
I'd use a function + recursion to make it a little more flexible:
function foo($check, $max, $end) {
if ($check%$max == 0 && $max >= $end){
if ($max == $end) {
return $check;
}
return foo($check, $max-1, $end);
}
}
for ($i=1; $i<=999999;$i++) {
$res = foo($i, 12, 2);
if ($res) break;
}
echo $res;
?>
Upvotes: 0
Reputation: 120704
Here you go:
for ($i = 1, $num = 12; $i <= 999999; $i++, $num += 12) {
if ($num % 11 || $num % 10 || $num % 9 || $num % 8 || $num % 7)
continue;
echo $num;
break;
}
Upvotes: 1
Reputation: 212482
Perhaps something like:
$max = 12;
$num = $max;
while(true) {
for($i = 2; $i <= $max; ++$i) {
if ($num % $i !== 0) break;
}
if ($i > $max) break;
$num += $max;
}
var_dump($num);
Upvotes: 2
Reputation: 3120
<?php
for ($i = 1; $i < 999999; $i++) {
$num = 12 * $i;
$divisible = true;
for ($j = $num; $j > 1; $j --) {
if ($num % $j !== 0) {
$divisible = false;
break;
}
}
if ($divisible === true) {
echo $num;
break;
}
}
Upvotes: 0