1

How to store the Fibonacci series of a number in an array in Remix IDE ?

2
  • You want an example to compute them right ?
    – hroussille
    Apr 11, 2022 at 13:02
  • Yes thats right !
    – Sandeep
    Apr 12, 2022 at 14:53

1 Answer 1

1

I think this might be what you are looking for : it computes the fibonacci sequence up to Fib(n) and returns an array with all the elements from 0 to n :

// SPDX-License-Identifier: MIT
pragma solidity ^0.8;

contract Fibonacci {

    function fibonacci(uint256 n) public pure returns (uint256[] memory) {
        require(n > 1, "n must be > 1");

        uint256[] memory sequence = new uint256[](n + 1);

        // Fib(0) = 0
        sequence[0] = 0;

        // Fib(1) = 1
        sequence[1] = 1;

        // Fib(n) = Fib(n - 1) + Fib(n - 2)
        for (uint256 i = 2; i < sequence.length; i++) {
            sequence[i] = sequence[i - 1] + sequence[i - 2];
        }

        return sequence;
    }
}

There are other ways to compute it, but this one is the simplest. I wouldn't recommend the recursive approach due to strict limitation on the EVM stack depths.

I hope that answers your question.

1
  • Yes got it...Thank you so much ! :)
    – Sandeep
    Apr 13, 2022 at 8:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.