Run ❯
Get your
own
website
×
Change Orientation
Change Theme, Dark/Light
Go to Spaces
Python
C
Java
def F(n): if memo[n] != None: # Already computed return memo[n] else: # Computation needed print('Computing F('+str(n)+')') if n <= 1: memo[n] = n else: memo[n] = F(n - 1) + F(n - 2) return memo[n] memo = [None]*7 print('F(6) = ',F(6)) print('memo = ',memo) #Python
#include
#include
int memo[7]; char computed[7] = {0}; // Tracks whether the value has been computed int F(int n) { if (computed[n]) { // Already computed return memo[n]; } else { // Computation needed printf("Computing F(%d)\n", n); if (n <= 1) { memo[n] = n; computed[n] = 1; // Mark as computed } else { memo[n] = F(n - 1) + F(n - 2); computed[n] = 1; // Mark as computed } return memo[n]; } } int main() { printf("F(6) = %d\n", F(6)); printf("memo = ["); for (int i = 0; i < 7; i++) { if (i > 0) { printf(", "); } if (computed[i]) { printf("%d", memo[i]); } else { printf("None"); } } printf("]\n"); return 0; } //C
public class Main { private static Integer[] memo = new Integer[7]; // Use Integer to allow null values public static void main(String[] args) { System.out.println("F(6) = " + F(6)); System.out.print("memo = ["); for (int i = 0; i < memo.length; i++) { if (i != 0) { System.out.print(", "); } System.out.print(memo[i]); } System.out.println("]"); } public static int F(int n) { if (memo[n] != null) { // Already computed return memo[n]; } else { // Computation needed System.out.println("Computing F(" + n + ")"); if (n <= 1) { memo[n] = n; } else { memo[n] = F(n - 1) + F(n - 2); } return memo[n]; } } } //Java
Python result:
C result:
Java result:
Computing F(6)
Computing F(5)
Computing F(4)
Computing F(3)
Computing F(2)
Computing F(1)
Computing F(0)
F(6) = 8
memo = [0, 1, 1, 2, 3, 5, 8]
Computing F(6)
Computing F(5)
Computing F(4)
Computing F(3)
Computing F(2)
Computing F(1)
Computing F(0)
F(6) = 8
memo = [0, 1, 1, 2, 3, 5, 8]
Computing F(6)
Computing F(5)
Computing F(4)
Computing F(3)
Computing F(2)
Computing F(1)
Computing F(0)
F(6) = 8
memo = [0, 1, 1, 2, 3, 5, 8]