Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- declare(strict_types=1);
- /*
- * The number of bytes in an integer determines the number of iterations that can be requested.
- * Once the computed value no longer fits in an integer, PHP will automatically convert to use
- * floating point representation, which means that the result is no longer accurate.
- * An alternative to imposing these limits would be to use the GNU MP library.
- */
- function fibonacci(int $iterations): Generator
- {
- if (
- $iterations <= 0
- || (PHP_INT_SIZE == 4 && $iterations > 47) // max iterations for 32-bit int
- || $iterations > 92 // assume 64-bit int
- ) {
- throw new ValueError('Invalid number of iterations specified');
- }
- $num1 = 0; // seed the initial values
- $num2 = 1;
- while ($iterations--) {
- yield $num1;
- $num2 = $num2 + $num1;
- $num1 = $num2 - $num1;
- }
- }
- foreach (fibonacci(10) as $number) {
- echo $number, ' ';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement