Skip to content

Instantly share code, notes, and snippets.

@pmgupte
Last active December 22, 2015 03:29
Show Gist options
  • Save pmgupte/6410730 to your computer and use it in GitHub Desktop.
Save pmgupte/6410730 to your computer and use it in GitHub Desktop.
My PHP solution to Project Euler problem # 2 - http://projecteuler.net/problem=2 - 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 m…
<?php
$n1 = 1;
$n2 = 1;
$n3 = $n1 + $n2;
$sum = 0;
while($n3 < 4000000) {
$sum += $n3;
$n1 = $n2 + $n3;
$n2 = $n1 + $n3;
$n3 = $n1 + $n2;
}
echo $sum;
?>
<?php
$n1 = 1;
$n2 = 2;
$sum = 2;
$i = 2;
while($i < 4000000) {
$i = $n1 + $n2;
$n1 = $n2;
$n2 = $i;
if ($i%2 == 0) {
$sum += $i;
}
}
echo $sum;
?>
@pmgupte
Copy link
Author

pmgupte commented Sep 2, 2013

sol-2 takes 0.00013589859008789 to execute.
original solution takes 0.00013208389282227

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment