I got the solution; however, I feel like the code is pretty awful. This is within my first 50 hours using any programming language…please bear with me.
The Problem:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
My Solution:
<?php
//if number is odd, returns false
function setOddsZero($n) {
$test = ($n&1); //0 = even, 1 = odd
if($test == 1) {
return false;
} else {
$n = $n;
}
}
$numbers=array(1,);
for($i>0; $i<=100; $i++) {
$numbers[$i] += (($numbers[$i-2])+($numbers[$i-1]));
if (($numbers[$i]) >= 4000000) {
echo $total;
die;
} else {
if((setOddsZero($numbers[$i]))===false) {
$total += 0;
}else {
$total += $numbers[$i];
}
}
}
?>
Less stack-pushy-shify (and thus more efficient) approach, as suggested by meze:
Edit: Modified the code to use
& 1instead of% 2, cf. this thread at devshed.