Need help with automatic recursive function

You have some syntax errors in your code which may be the cause of your issue.

Here is a complete example which works on all 4 simulators on EDA Playground.

module testbench();
  static int mem[int];

  function automatic int factorial_mem(int n);
    int result;
    
    $display("Factoring %0d", n);
    if (mem.exists(n))  $display("Exists %0d", n);
    $display("Memory size is %0d", mem.size());
    
    if((n===0) || (n===1))
      return 1;    
    else if (mem.exists(n)) begin
      $display("I remember this n=%0d", n);
      return mem[n];
    end
    else if (n>0) begin
      result = n*factorial_mem(n-1);
      mem[n] = result;
      $display("Assign mem[%0d] %0d", n,mem[n]);
      return result;
    end
  endfunction
  
  initial begin
    $display("Fact = %0d", factorial_mem(3));
    $display("Fact = %0d", factorial_mem(10));
    $display("Fact = %0d", factorial_mem(5));
    $display("Fact = %0d", factorial_mem(7));
  end
endmodule
1 Like