Completed
Pull Request — dev (#23)
by Jordan
02:47
created

Collections::fibonacciCollection()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 0
cts 20
cp 0
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 15
nc 4
nop 1
crap 20
1
<?php
2
3
namespace Samsara\Fermat;
4
5
use Samsara\Fermat\Types\NumberCollection;
6
7
class Collections
8
{
9
10
    /**
11
     * Returns a NumberCollection object with the first $terms terms of the Fibonacci sequence (OEIS: A000045)
12
     *
13
     * NOTE: If what you need is JUST the nth term of this sequence, use the SequenceProvider::nthFibonacciNumber()
14
     * function which is much faster at calculating only that term, especially much later in the sequence.
15
     *
16
     * @param int $terms
17
     * @return NumberCollection
18
     */
19
    public static function fibonacciCollection(int $terms): NumberCollection
20
    {
21
        $collection = new NumberCollection();
22
23
        $k1 = Numbers::makeZero();
24
        $k2 = Numbers::makeOne();
25
26
        if ($terms == 1) {
27
            $collection->push($k1);
28
        } else {
29
            $collection->push($k1)->push($k2);
30
        }
31
32
        if ($terms > 2) {
33
            for ($n = 2;$n < $terms;$n++) {
34
                $kN = $k1->add($k2);
35
                $collection->push($kN);
36
37
                $k1 = $k2;
38
                $k2 = $kN;
39
            }
40
        }
41
42
        return $collection;
43
    }
44
45
}