Memoization for Fibonacci's series

Hello everyone. This is actually the 1st time i use this forum, i hope it works. Below is the code i tried to write and why it doesn’t work (i’m not able to understand the reason). Thanks for helping me out. Sorry for my bad English.
Create a memoized fibMemo() function. This function should return the n th Fibonacci number.

import java.util.HashMap;

import java.util.Map;

public class fibMemo {

  public static void main(String[] args) {

    Map<Integer, Integer> map = new HashMap<Integer, Integer>();

    System.out.println(fibMemo(10, map));

    map = new HashMap<Integer, Integer>();

    System.out.println(fibMemo(20, map));

  }

  public static int fibMemo(int n, Map<Integer, Integer> map) {

if (n==0 | n==1){

  return n;

}

if (map.containsKey(n)){

  return map.get(n);

}

else 

fibMemo(n)= fibMemo(n-1)+fibMemo(n-2);

map.put(n, fibMemo(n));

    return n;

  }

}

fibMemo.java:22: error: method fibMemo in class fibMemo cannot be applied to given types;
fibMemo(n)= fibMemo(n-1)+fibMemo(n-2);
^
required: int,Map<Integer,Integer>
found: int
reason: actual and formal argument lists differ in length
fibMemo.java:22: error: method fibMemo in class fibMemo cannot be applied to given types;
fibMemo(n)= fibMemo(n-1)+fibMemo(n-2);
^
required: int,Map<Integer,Integer>
found: int
reason: actual and formal argument lists differ in length
fibMemo.java:22: error: method fibMemo in class fibMemo cannot be applied to given types;
fibMemo(n)= fibMemo(n-1)+fibMemo(n-2);
^
required: int,Map<Integer,Integer>
found: int
reason: actual and formal argument lists differ in length
fibMemo.java:23: error: method fibMemo in class fibMemo cannot be applied to given types;
map.put(n, fibMemo(n));
^
required: int,Map<Integer,Integer>
found: int
reason: actual and formal argument lists differ in length
4 errors

Hello!

There are many problems in your code:

  1. Don’t use the same method name as the class name. This name is reserved for the constructor.
  2. In the line fibMemo(n)= fibMemo(n-1)+fibMemo(n-2); you are trying to assign a value to another value, which is not correct. Here you need to use a new variable.
  3. In the recursive calls to fibMemo, you forgot to specify the second argument - map.
  4. Instead of a computed value, you return the numeric position n from fibMemo.
  5. I think you forgot the curly braces in the else branch. Always use curly braces in conditions to avoid misunderstandings and mistakes.
  6. Before the second call to fibMemo in main you create a new map so the values ​​from the first call will not be reused.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.