Algorithm
First Let's look a Basic fibonacci series to get a clearer example of Fibonacci Sequence -
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Fibonacci Formula is:
Fn = Fn-1 + Fn-2
Let's See the sequence:
- f(0) = 0 (assume)
- f(1) = 1
- f(2) = f(1) + f(0) = 1
- f(3) = f(2) + f(1) = 1 + 1 = 2
- f(4) = f(3) + f(2) = 2 + 1 = 3
- f(5) = f(4) + f(3) = 3 + 2 = 5
- f(6) = f(5) + f(4) = 5 + 3 = 8
- f(7) = f(6) + f(5) = 8 + 5 = 13
- f(8) = f(7) + f(6) = 13 + 8 = 21
- and ongoging like this Fn = Fn-1 + Fn-2
Code Examples
#1 Code Example with PHP Programming
Code -
PHP Programming
function fibonacci($howMany) {
$i = 1;
$n1 = 0;
$n2 = 1;
$nextNo;
echo "Fibonacci Series Are : ";
for ($i = 1; $i < = $howMany; ++$i) {
echo $n1 . ', ';
$nextNo = $n1 + $n2;
$n1 = $n2;
$n2 = $nextNo;
}
}
echo fibonacci(10); // 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Copy The Code &
Try With Live Editor
Input
10
Output
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
#2 Fibonacci Series using PHP with Array and Class
Code -
PHP Programming
declare(strict_types=1);
namespace App\PhpTest;
class Fibonacci
{
public array $numbers;
public function __construct()
{
$this->numbers = [];
}
/**
* Generate fibonacci number series.
*
* @param integer $limit
* @return self
*/
public function generate(int $limit = 10): self
{
$firstNum = 0;
$secondNum = 1;
$fib = 0;
// Add the initial numbers also in the fib array.
$this->numbers[] = $firstNum;
if ($limit === 1) {
return $this;
}
$this->numbers[] = $secondNum;
for ($i = 2; $i < $limit; $i++) {
$fib = $firstNum + $secondNum;
$firstNum = $secondNum;
$secondNum = $fib;
$this->numbers[] = $fib;
}
return $this;
}
/**
* Converts generated results to array.
*
* @return array
*/
public function toArray(): array
{
return (array) $this->numbers;
}
}
// Then use anywhere like so -
$fibonacci = new Fibonacci();
$fibonacci->generate(10)->toArray();
Copy The Code &
Try With Live Editor
Input
10
Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
#3 Writing Test code for above fibonacci number series in PHP
Code -
PHP Programming
declare(strict_types=1);
namespace App\PhpTest\Tests;
use App\PhpTest\Fibonacci;
use PHPUnit\Framework\TestCase;
class FibonacciTest extends TestCase
{
public Fibonacci $fibonacci;
/**
* This method is called before each test.
*/
protected function setUp(): void
{
$this->fibonacci = new Fibonacci();
}
/**
* Test if fibonacci numbers generated properly.
*
* @dataProvider dataProviderForCheckFibonacciNumbers
*/
public function testCheckFibonacciNumber(int $limit = 10, array $expectation): void
{
$this->assertEquals(
$expectation,
$this->fibonacci->generate($limit)->toArray()
);
}
public function dataProviderForCheckFibonacciNumbers(): array
{
return [
'Get 1 fibonacci numbers are:' => [1, [0]],
'Get 2 fibonacci numbers are:' => [2, [0, 1]],
'Get 10 fibonacci numbers are:' => [10, [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]],
];
}
}
Copy The Code &
Try With Live Editor
Input
10
Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Demonstration
Fibonacci Problem Solution using PHP Language