views:

359

answers:

4

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;
 }
}
A: 

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

cruizer
+1  A: 

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

should be

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

Greg
A: 

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.

David Grant
+1  A: 

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.

Gumbo
Well it can cut both ways...it might pass the test for the smaller numbers (2, 3, etc.) only to fail the test for the bigger ones. if you can isolate only the prime factors from 2 to 14 and test for divisibility with only those, then it can probably be a bit faster
cruizer