A fibonacci tree, done with a php class. I first checked the sites on fibonacci routines but could not find a php version I could comprehend so I made one with some simple classes :
Class Fibonacci {
var $Fibs = array();
public function __construct($code) {
$this->recurse($code);
}
public function recurse($n) {
if($n==1 || $n==2) {
$this->Fibs[$n]->myValue = 1;
return 1;
} else {
$this->recurse($n-1);
$this->recurse($n-2);
$this->Fibs[$n]->myValue = $this->Fibs[$n-1]->myValue + $this->Fibs[$n-2]->myValue;
return $this->Fibs[$n]->myValue;
}
}
public function Fibs($code) {
if (!$this->Fibs[$code])
{
$this->Fibs[$code] = new Fib($code);
}
return $this->Fibs[$code];
}
}
Class Fib {
var $myFib;
var $myValue;
public function __construct($code) {
$this->myFib = $code;
}
}
I was rather surprised when it actually worked.
It iterates once and digs down to nodes(0, 1), returns the values of the two preceding nodes as any node’s value and sums back up to the node I enter. This way it calculates the tree once, then I retrieve values by referencing a node.
$F = new Fibonacci(7);
echo $F->Fibs(7)->myValue;
echo $F->Fibs(6)->myValue;
here is a normal sample from the IBM site
function fib($nth = 1) {
static $fibs = array();
if ( ! empty ($fibs[$nth] ) ) {
return( $fibs[$nth] );
}
if ( $nth < 2 ) {
$fibs[$nth] = $nth;
}
else {
$fibs[$nth - 1] = fib( $nth - 1 );
$fibs[$nth - 2] = fib( $nth - 2 );
$fibs[$nth] = $fibs[$nth - 1] + $fibs[$nth -2];
}
return( $fibs[$nth] );
}