vendredi 6 mars 2015

changes the recursive function in this fibonacci code


So I made some changes to the previous question I posted. right now my code is based on the fibonacci code,



unsigned int fib(unsigned int n)
{
if (n==1 || n == 2)
return 1;
else
return fib(n-2) + fib(n-1)
}


I need to write the cursive in assembly x86 to get the nth number in sequence. and a main function in c++ read postive int n, then call the mobonacci function with parameter n, then display result.


But now the function need to changed to Mobonacci, its like fibonacci but the sequence is now f(n-2)/2 + f(n-1) * 2. So the sequence become 1, 2, 4, 9, 20, 44......


so now how can fibonacci be changed to mobonacci like above? also feel free to correct my code if you see anything wrong.


Here is my code:



include Irvine32.inc

.code
main PROC
mov ecx,0
push 10 ; calculate the nth fib
call fib ;
add esp, 4 ;

call WriteDec
call Crlf
exit
main ENDP

fib PROC C
add ecx,1
push ebp
mov ebp,esp
sub esp, 4 ; space for a local dword [ebp-4]
mov eax,[ebp+8] ;

; if ((n == 1) || (n == 2)) return 1;
cmp eax,2 ;
je exception2
cmp eax,1 ;
je exception2

;else return fib(n-1) + fib(n-2);
dec eax
push eax ; Fib(n-1)
call fib
mov [ebp-4], eax ; store first result

dec dword ptr [esp] ;
call fib
add esp, 4 ;

add eax, [ebp-4] ; add result and stored first result

jmp Quit

exception2:
mov eax, 1 ; start values: 1, 1
; dec eax ; start values: 0, 1
Quit:
mov esp, ebp ;
pop ebp ;

ret ;
fib ENDP

END main



Aucun commentaire:

Enregistrer un commentaire