What’s the 1,337th number in the Fibonacci sequence? It’s 1.1667830241021E+279, of course!
Here’s an cool snippet of PHP code I wrote several months ago which implements not only PHP’s Iterator interface to provide an lazily-iterable list of Fibonacci numbers, but also the ArrayAccess interface and some fancy math to provide indexed access, too. Lazy evaluation is pretty cool because it saves memory. In this case, in effect you have an array of 1,478 of elements (bound only by the capacity of float values) while only using 984 bytes of memory for the object:
<?php class Fibonacci implements Iterator, ArrayAccess { const PHI = 1.618033989; private $a; private $b; private $i; public function __construct() { } public function rewind() { $this->a = 1; $this->b = 0; $this->i = 0; } public function current() { return $this->b; } public function key() { return $this->i; } public function next() { $this->i++; $tmp = $this->a + $this->b; $this->a = $this->b; $this->b = $tmp; } public function valid() { return $this->offsetExists($this->i); } public function offsetExists($i) { // Fib(1476) = float(1.30698922376E+308) // Fib(1477) = float(INF) return $i > -1 && $i < 1478; } public function offsetGet($i) { // en.wikipedia.org/wiki/Fibonacci_number#Computation_by_rounding return floor((pow(self::PHI, $i) / sqrt(5)) + 0.5); } public function offsetSet($i, $val) { throw new Exception("sequence is read-only"); } public function offsetUnset($i) { throw new Exception("sequence is read-only"); } } $mem = memory_get_usage(); $fib = new Fibonacci(); echo "Memory used for Fibonacci object: " . (memory_get_usage() - $mem) . "\n"; echo "The 1337th number in the sequence is: " . $fib[1337] . "\n"; echo "Here is the sequence:\n"; foreach ($fib as $i => $f) { var_dump($f); }
Comments
Post a Comment