Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
12 / 12 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
| Fibonacci | |
100.00% |
12 / 12 |
|
100.00% |
3 / 3 |
7 | |
100.00% |
1 / 1 |
| __construct | n/a |
0 / 0 |
n/a |
0 / 0 |
1 | |||||
| isFibonacci | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
2 | |||
| fib | |
100.00% |
10 / 10 |
|
100.00% |
1 / 1 |
3 | |||
| binet | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | /** |
| 3 | * Jingga |
| 4 | * |
| 5 | * PHP Version 8.1 |
| 6 | * |
| 7 | * @package phpOMS\Math\Functions |
| 8 | * @copyright Dennis Eichhorn |
| 9 | * @license OMS License 2.0 |
| 10 | * @version 1.0.0 |
| 11 | * @link https://jingga.app |
| 12 | */ |
| 13 | declare(strict_types=1); |
| 14 | |
| 15 | namespace phpOMS\Math\Functions; |
| 16 | |
| 17 | use phpOMS\Math\Number\Numbers; |
| 18 | |
| 19 | /** |
| 20 | * Well known functions class. |
| 21 | * |
| 22 | * @package phpOMS\Math\Functions |
| 23 | * @license OMS License 2.0 |
| 24 | * @link https://jingga.app |
| 25 | * @since 1.0.0 |
| 26 | */ |
| 27 | final class Fibonacci |
| 28 | { |
| 29 | /** |
| 30 | * Constructor. |
| 31 | * |
| 32 | * @since 1.0.0 |
| 33 | * @codeCoverageIgnore |
| 34 | */ |
| 35 | private function __construct() |
| 36 | { |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * Is Fibonacci number. |
| 41 | * |
| 42 | * @param int $n Integer |
| 43 | * |
| 44 | * @return bool |
| 45 | * |
| 46 | * @since 1.0.0 |
| 47 | */ |
| 48 | public static function isFibonacci(int $n) : bool |
| 49 | { |
| 50 | return Numbers::isSquare(5 * $n ** 2 + 4) || Numbers::isSquare(5 * $n ** 2 - 4); |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Get n-th Fibonacci number. |
| 55 | * |
| 56 | * @param int $n n-th number |
| 57 | * @param int $start Start value |
| 58 | * |
| 59 | * @return int |
| 60 | * |
| 61 | * @since 1.0.0 |
| 62 | */ |
| 63 | public static function fib(int $n, int $start = 1) : int |
| 64 | { |
| 65 | if ($n < 3) { |
| 66 | return $start; |
| 67 | } |
| 68 | |
| 69 | $old1 = $start; |
| 70 | $old2 = $start; |
| 71 | $fib = 0; |
| 72 | |
| 73 | for ($i = 2; $i < $n; ++$i) { |
| 74 | $fib = $old1 + $old2; |
| 75 | $old1 = $old2; |
| 76 | $old2 = $fib; |
| 77 | } |
| 78 | |
| 79 | return $fib; |
| 80 | } |
| 81 | |
| 82 | /** |
| 83 | * Calculate n-th Fibonacci with binets formula. |
| 84 | * |
| 85 | * @param int $n n-th number |
| 86 | * |
| 87 | * @return int |
| 88 | * |
| 89 | * @since 1.0.0 |
| 90 | */ |
| 91 | public static function binet(int $n) : int |
| 92 | { |
| 93 | return (int) (((1 + \sqrt(5)) ** $n - (1 - \sqrt(5)) ** $n) / (2 ** $n * \sqrt(5))); |
| 94 | } |
| 95 | } |