Question

problem euler #5

i found the solution but i don't know why this first code is faster (i put 14 in order to try to make more clear the code) the only difference is that i eliminate the for i wrote for a huge if

if($num%14==0 && $num%13==0 &&$num%12==0 &&$num%11==0 &&$num%10==0 && $num%9==0 && $num%8==0 && $num%7==0 && $num%6==0 && $num%5==0 && $num%4==0 && $num%3==0 && $num%2==0 && $num%1==0){
    $notFound=0;
}

why is this second code hugely more slow than the first one? With the for it suppose to be faster. is the same in another languages???

$notFound=0;
for ( $i=14; $i>=2 && notFound==0; $i--){
    if($num%$i!=0){
        $notFound=1;
    }
}
Was it helpful?

Solution

The second code sample is simply performing more operations than the first, so I'd expect it to be slower. In this situation, you'd find that whilst offering poorer performance, a for loop offers significantly better readability and maintainability.

OTHER TIPS

for ( $i=14; $i>=2 && notFound==0; $i--){

should be

for ( $i=14; $i>=2 && $notFound==0; $i--){

I would go from the smallest to the largest number. Because if a number is divisible by 14 it is also divisible by 2.

$notFound = 0;
for ($i=2; $i<=14; $i++) {
    if ($num % $i !== 0) {
        $notFound = 1;
        break;
    }
}

By doing this you can exclude the numbers as early as possible.

I think this is due to the interpreter overhead with PHP (with it having to parse and execute the for loop).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top