ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Solidity Recursive Fibonacci

Solidity

Goal -- WPM

Ready
Exercise Algorithm Area
1pragma solidity ^0.8.0;
2
3contract RecursiveFibonacci {
4
5mapping(uint256 => uint256) private memo;
6
7/**
8* @dev Calculates the Nth Fibonacci number using recursion with memoization.
9* This function is designed to be gas-efficient by storing previously computed values.
10* @param n The index of the Fibonacci number to compute (0-indexed).
11* @return The Nth Fibonacci number.
12*/
13function fibonacci(uint256 n) public returns (uint256) {
14// Base cases
15if (n == 0) {
16return 0;
17}
18if (n == 1) {
19return 1;
20}
21
22// Check if the value is already memoized
23if (memo[n] != 0) {
24return memo[n];
25}
26
27// Recursive step with memoization
28// Calculate fib(n-1) and fib(n-2) recursively
29uint256 fibNMinus1 = fibonacci(n - 1);
30uint256 fibNMinus2 = fibonacci(n - 2);
31
32// Store the result before returning
33memo[n] = fibNMinus1 + fibNMinus2;
34
35return memo[n];
36}
37
38/**
39* @dev Clears the memoization cache.
40* This function can be useful for resetting the state if needed.
41*/
42function clearMemo() public {
43// This is a simplified clearing mechanism. For large mappings,
44// a more complex approach might be needed to avoid gas limits.
45// However, for typical use cases, iterating and setting to 0 is sufficient.
46for (uint256 i = 0; i < 1000; i++) { // Limit iteration to avoid gas issues
47if (memo[i] != 0) {
48delete memo[i];
49}
50}
51// Note: For a truly dynamic clear, one might need to store keys separately.
52}
53
54/**
55* @dev Helper function to get a memoized value without recursion.
56* Primarily for testing or debugging purposes.
57* @param n The index to retrieve.
58* @return The memoized value or 0 if not computed.
59*/
60function getMemoizedValue(uint256 n) public view returns (uint256) {
61require(n < 1000, "Index out of memo bounds for this helper."); // Safety check
62return memo[n];
63}
64}
Algorithm description viewbox

Solidity Recursive Fibonacci

Algorithm description:

This Solidity contract computes Fibonacci numbers using a recursive approach enhanced with memoization. The Fibonacci sequence is defined by F(0) = 0, F(1) = 1, and F(n) = F(n-1) + F(n-2) for n > 1. Memoization stores previously computed Fibonacci numbers in a mapping, significantly reducing redundant calculations and improving performance, especially for larger values of 'n'. This pattern is vital for optimizing recursive algorithms in resource-constrained environments like blockchains.

Algorithm explanation:

The `fibonacci` function calculates the Nth Fibonacci number. It employs recursion with memoization to avoid recalculating values. The base cases are `n = 0` returning 0 and `n = 1` returning 1. For `n > 1`, it first checks if `memo[n]` is already populated (i.e., not 0). If it is, the stored value is returned directly. Otherwise, it recursively calls `fibonacci(n - 1)` and `fibonacci(n - 2)`, sums their results, stores this sum in `memo[n]`, and then returns it. This memoization drastically reduces the number of function calls from exponential (O(2^n)) to linear (O(n)). The space complexity is also O(n) due to the storage of computed values in the `memo` mapping. The `clearMemo` function provides a way to reset the cache, though it has limitations for very large caches due to gas costs. The `getMemoizedValue` is a view helper for inspection.

Pseudocode:

Function fibonacci(n):
  If n is 0:
    Return 0
  If n is 1:
    Return 1
  If memo[n] is not 0:
    Return memo[n]
  result = fibonacci(n - 1) + fibonacci(n - 2)
  memo[n] = result
  Return result