Fibonacci Series Using SystemVerilog

Hi, it has been really a while now. Recently, I’ve been refreshing my SystemVerilog skills. Using SystemVerilog to calculate Fibonacci Series seems to get asked a lot during interviews. I think I might just write these down for future reference.

There are two ways to do this problem. The first one is using recursion, and the other one is using dynamic programming. The codes are listed in the following:

  1. Recursion
program automatic fibonacci;

function int fib(int i);

if(i == 0 || i ==1)

fib = i;


fib = fib(i-1)+fib(i-2);

endfunction: fib



2. Dynamic Programming

I am using a dynamic array to store the calculated Fibonacci numbers. You need to initialize it before using it.

int f[];

function int dy_fib(int i);

f[0] = 0;

f[1] = 1;

for(int j = 2; j <= i; j++) begin

f[j] = f[j-1] + f[j-2];


dy_fib = f[i];

endfunction: dy_fib


For the for loop, j is less or equal than i. I am not sure why it’s not shown properly in the code plugin here. I’ll try to fix it later.

Above are the codes for calculating Fibonacci Series in SystemVerilog. Leave me a comment if you have any questions.


Leave a Reply

Your email address will not be published. Required fields are marked *