Solidity Exercise - Fabonacci

Posted by Bourne's Blog - A Full-stack & Web3 Developer on May 14, 2024

Fabonacci

This exercise assumes you understand what Fibonacci sequence is.

  1. Function fibonacci takes a uint256 as argument and returns nth fibonacci number.

Fibonacci sequence are 0,1,1,2,3,5,8,13,….

calling fibonacci(6) would return 8, because the 6th Fibonacci number is 8.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.13;

contract Fibonacci {
    /*
        This exercise assumes you understand what Fibonacci sequence is.
        1. Function `fibonacci` takes a uint256 as argument and returns nth fibonacci number.
        
        Fibonacci sequence are 0,1,1,2,3,5,8,13,....
        
        calling fibonacci(6) would return 8, because the 6th Fibonacci number is 8.
    */

    function fibonacci(uint256 _position) public view returns (uint256) {
        // your code here
    }
}

Problem Analysis

It’s a common programming subject to calculate recursive problem.

Algorism is: if the _position == 0, return 0; if the _position == 1, return 1; else just return fabonacci(n - 1) + fabonacci(n - 2);

Coding

1
2
3
4
5
6
7
8
9
10
    function fibonacci(uint256 _position) public view returns (uint256) {
        // your code here
        if (_position == 0) {
            return 0;
        }else if (_position == 1) {
            return 1;
        }else{
            return fibonacci(_position-1) + fibonacci(_position - 2);
        }
    }

Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.13;

import "forge-std/Test.sol";
import "../src/Fibonacci.sol";

contract FibonacciTest is Test {
    Fibonacci public fibonacci;

    function setUp() public {
        fibonacci = new Fibonacci();
    }

    function testFibonacci() external {
        uint256 result = fibonacci.fibonacci(4);
        uint256 result1 = fibonacci.fibonacci(10);
        uint256 result2 = fibonacci.fibonacci(20);
        uint256 result3 = fibonacci.fibonacci(1);

        assertEq(result, 3, "expected result to be 3");
        assertEq(result1, 55, "expected result to be 55");
        assertEq(result2, 6765, "expected result to be 6765");
        assertEq(result3, 1, "expected result to be 1");
    }
}
1
2
3
4
5
6
7
8
9
10
11
➜  Fibonacci git:(main) ✗ forge test -vvv
[⠊] Compiling...
[⠘] Compiling 19 files with Solc 0.8.25
[⠃] Solc 0.8.25 finished in 808.49ms
Compiler run successful!

Ran 1 test for test/Fibonacci.t.sol:FibonacciTest
[PASS] testFibonacci() (gas: 4248870)
Suite result: ok. 1 passed; 0 failed; 0 skipped; finished in 22.44ms (17.85ms CPU time)

Ran 1 test suite in 211.72ms (22.44ms CPU time): 1 tests passed, 0 failed, 0 skipped (1 total tests)

Reference: Solidity Exercise - Fibonacci