Advertisement
neil_pearce

Fibonacci sequence

Feb 7th, 2023
1,291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.96 KB | None | 0 0
  1. <?php
  2. declare(strict_types=1);
  3.  
  4. /*
  5.  * The number of bytes in an integer determines the number of iterations that can be requested.
  6.  * Once the computed value no longer fits in an integer, PHP will automatically convert to use
  7.  * floating point representation, which means that the result is no longer accurate.
  8.  * An alternative to imposing these limits would be to use the GNU MP library.
  9.  */
  10.  
  11. function fibonacci(int $iterations): Generator
  12. {
  13.     if (
  14.         $iterations <= 0
  15.         || (PHP_INT_SIZE == 4 && $iterations > 47)  // max iterations for 32-bit int
  16.         || $iterations > 92  // assume 64-bit int
  17.     ) {
  18.         throw new ValueError('Invalid number of iterations specified');
  19.     }
  20.  
  21.     $num1 = 0;  // seed the initial values
  22.     $num2 = 1;
  23.  
  24.     while ($iterations--) {
  25.         yield $num1;
  26.  
  27.         $num2 = $num2 + $num1;
  28.         $num1 = $num2 - $num1;
  29.     }
  30. }
  31.  
  32.  
  33. foreach (fibonacci(10) as $number) {
  34.     echo $number, ' ';
  35. }
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement