assemblyfibonaccirisc

assembly program for Fibonacci


I just got a question about the assembly program for Fibonacci sequence. The question is as following : The Fibonacci sequence F is defined as F(1) = F(2) = 1 and for n ≥ 2, F(n + 1) = F(n) + F(n − 1) i.e., the (n + 1)th value is given by the sum of the nth value and the (n − 1)th value.

  1. Write an assembly program typical of RISC machines for computing the kth value F(k), where k is a natural number greater than 2 loaded from a memory location M, and storing the result at memory location M.

I received the answer of following:

   LOAD r2, M
   LOAD r0, #1
   LOAD r1, #1

4: SUB r2, r2, #1
   ADD r3, r0, r1
   LOAD r0, r1
   LOAD r1, r3
   BNE 4, r2, #2 // jump to instruction 4 if r2 is not equal to 2

   STOR M, r1

where # indicates immediate addressing and BNE stands for "branch if not equal".

I do not understand why... Can anyone please explain it to me?


Solution

  • The code is perfectly correct. Here is a commented version that may answer your questions.

       LOAD r2, M     ; R2 -> k (as F(K) has to be computed)
       LOAD r0, #1    ; F(1)=1 -> r0 
       LOAD r1, #1    ; F(2)=1 -> r1 
                      ; As F(1) and F(2) are already computed, we start at i=2
                      ; During al the computation of F(i) r1==F(i-1) and r0== F(i-2)
    
    4: SUB r2, r2, #1 ; k-- 
       ADD r3, r0, r1 ; F(i)=F(i-2)+F(i-1)
                      ; F(i) computed, prepare next iteration (implicitely i++)
       LOAD r0, r1    ; F(i-2)=r1 (previously F(i-1))
       LOAD r1, r3    ; F(i-1)=r3 (just computed F(i))
       BNE 4, r2, #2 // jump to instruction 4 if r2 (k) is not equal to 2
                      ; because we have started at i==2 we must perform
                      ; k-2 iterations. 
       STOR M, r1
    

    Note that i never appears, but it is simpler to think of it, instead of k that is decremented.