Skip to content

Instantly share code, notes, and snippets.

@pstuifzand
Created July 12, 2012 10:18
Show Gist options
  • Save pstuifzand/3097208 to your computer and use it in GitHub Desktop.
Save pstuifzand/3097208 to your computer and use it in GitHub Desktop.
Fibonacci for web developers
<?php
include "config.php";
$n = $_GET['n'];
if ($n == 1) {
echo "fib($n) == 1";
mysql_query("REPLACE INTO `fib` (`n`, `fib`) VALUES ('1','1')");
}
else if ($n == 2) {
echo "fib($n) == 1";
mysql_query("REPLACE INTO `fib` (`n`, `fib`) VALUES ('2','1')");
}
else {
$i = 3;
while ($i <= $n) {
$res = mysql_query("SELECT `fib` FROM `fib` WHERE `n` = '$i'");
if ($res) {
$row = mysql_fetch_assoc($res);
if (!$row['fib']) {
$a = $i - 1;
$res = mysql_query("SELECT `fib` FROM `fib` WHERE `n` = '$a'");
if ($res) {
$row = mysql_fetch_assoc($res);
$f1 = $row['fib'];
}
$b = $i - 2;
$res = mysql_query("SELECT `fib` FROM `fib` WHERE `n` = '$b'");
if ($res) {
$row = mysql_fetch_assoc($res);
$f2 = $row['fib'];
}
$fib = $f1+$f2;
mysql_query("REPLACE INTO `fib` (`n`, `fib`) VALUES ('$i','$fib')");
}
}
$i++;
}
$res = mysql_query("SELECT `fib` FROM `fib` WHERE `n` = '$n'");
if ($res) {
$row = mysql_fetch_assoc($res);
echo "fib($n) == " . $row['fib'];
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment