Skip to content
This repository was archived by the owner on Aug 22, 2025. It is now read-only.

Commit 67ba0e1

Browse files
author
Holger Lösken
committed
Add task6 in php
1 parent 2254507 commit 67ba0e1

File tree

4 files changed

+68
-1
lines changed

4 files changed

+68
-1
lines changed

README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,20 @@ _Do not_ use nested loops to solve this problem, because of a time complexity of
8787

8888
The result here is `7`.
8989

90+
### Task 6
91+
92+
Calculate the [Fibonacci number](https://en.wikipedia.org/wiki/Fibonacci_number) of a given number
93+
and return the last `6` non-zero numbers.
94+
95+
**Requirements:**
96+
97+
* Throw an exception when passing in a negative number
98+
99+
**Example:**
100+
101+
* `F8` = `21`, return `21`
102+
* `F38` = `39088169`, return `88169`
103+
90104
## Contribute
91105

92106
Feel free to contribute. Use the issue list to propose new tasks or open PRs. Just provide proper tests

src/php/composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@
1111
"t2/s1.php",
1212
"t3/s1.php",
1313
"t4/s1.php",
14-
"t5/s1.php"
14+
"t5/s1.php",
15+
"t6/s1.php"
1516
],
1617
"psr-4": {
1718
"Tests\\": "tests/"

src/php/t6/s1.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
function fib(int $n): int {
6+
if ($n < 0) {
7+
throw new Exception("Only non-negative integers are allowed");
8+
}
9+
10+
if($n <= 1) {
11+
return $n;
12+
}
13+
14+
return fibonacci($n-1) + fibonacci($n-2);
15+
}
16+
17+
function fibonacci(int $n): int {
18+
$result = fib($n);
19+
20+
$str = (string) $result;
21+
if (strlen($str) > 6 ) {
22+
return (int) substr($str, -6);
23+
}
24+
25+
return (int) $str;
26+
}

src/php/tests/T6Test.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Tests;
6+
7+
use Exception;
8+
use PHPUnit\Framework\TestCase;
9+
10+
final class T6Test extends TestCase
11+
{
12+
public function testFibonacci(): void
13+
{
14+
$this->assertSame(0, fibonacci(0));
15+
$this->assertSame(1, fibonacci(1));
16+
$this->assertSame(2, fibonacci(3));
17+
$this->assertSame(21, fibonacci(8));
18+
$this->assertSame(88169, fibonacci(38));
19+
}
20+
21+
public function testThrowException(): void
22+
{
23+
$this->expectException(Exception::class);
24+
fibonacci(-1);
25+
}
26+
}

0 commit comments

Comments
 (0)