Advertisement
Guest User

Timothy Boronczyk/zaemis

a guest
Dec 26th, 2010
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.21 KB | None | 0 0
  1. <?php
  2. class Fibonacci implements Iterator, ArrayAccess
  3. {
  4.     const PHI = 1.618033989;
  5.  
  6.     private $i;
  7.  
  8.     private $a;
  9.     private $b;
  10.  
  11.     public function __construct() {
  12.     }
  13.  
  14.     public function rewind() {
  15.         $this->i = 0;
  16.         $this->a = 1;
  17.         $this->b = 0;
  18.     }
  19.  
  20.     public function current() {
  21.         return $this->b;
  22.     }
  23.  
  24.     public function key() {
  25.        return $this->i;
  26.     }
  27.  
  28.     public function next() {
  29.         $this->i++;
  30.         $tmp = $this->a + $this->b;
  31.         $this->a = $this->b;
  32.         $this->b = $tmp;
  33.     }
  34.  
  35.     public function valid() {
  36.         return $this->offsetExists($this->i);
  37.     }
  38.  
  39.     public function offsetExists($i) {
  40.         // Fib(1476) = float(1.30698922376E+308)
  41.         // Fib(1477) = float(INF)
  42.         return $i > -1 && $i < 1478;
  43.     }
  44.  
  45.     public function offsetGet($i) {
  46.         // http://en.wikipedia.org/wiki/Fibonacci_number#Computation_by_rounding
  47.         return floor((pow(self::PHI, $i) / sqrt(5)) + 0.5);
  48.     }
  49.  
  50.     public function offsetSet($i, $val) {
  51.         throw new Exception("sequence is read-only");
  52.     }
  53.  
  54.     public function offsetUnset($i) {
  55.         throw new Exception("sequence is read-only");
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement