# How to get all the Fibonacci elements in an array in Solidity?

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

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

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.