Hi guys I have been working on this assignment and struggling. It is a remake of the the fib sequence the changes are that it goes f(n-2)/2+f(n-1)*2 and the starting two numbers are 1 and 2 so some of the sequence would be as follows. 1,2,4,9,20,44,98. We are to complete the multiplication and division using shift left and shift right (shl and shr) I feel like I am very close but my code for some reason will not read in a number that is over the value of 2 or at least that's how I am seeing it. If you could look and give me some direction on what could be causing this whether it be my actual formula part or the before and after thank you. The very first main is my simple way of just spewing out the result.
include Irvine32.inc
.code
main PROC
push 1
call fib
call WriteDec
call Crlf
push 2
call fib
call WriteDec
call Crlf
push 3
call fib
call WriteDec
call Crlf
push 4
call fib
call WriteDec
call Crlf
push 5
call fib
call WriteDec
call Crlf
push 7
call fib
call WriteDec
call Crlf
exit
main ENDP
fib PROC
push ebp
mov ebp, esp
mov ebx, [ebp+8] ;get number to calc that was pushed before
; if ((n == 1) || (n == 0)) return 1;
mov eax,1
cmp ebx,1
jle Quit
;else return fib(n-2)/2 + fib(n-1)*2;
valid:
;(n-2)/2
dec ebx ;n-1
dec ebx ; n-1 again so n-2
push ebx ; store the number
call fib ; calculate n-2
shr ebx,1 ;(n-2)/2
push eax ;store it away
mov ebx, [ebp+8] ;get number to calc
;(n-1)*2
dec ebx ;(n-1)
push ebx ;store the numebr
call fib ;calculate n-1
shl ebx,1 ;(n-1)*2
pop edx ;bring back the (n-2)*2 saved value
add eax,edx ;adds the n-2 and n-1 together
jmp Quit
Quit:
pop ebp ;return base pointer
ret 4 ;clean stack
fib ENDP
END main
To calculate f(n-2)/2 you need to use SHR in stead of SHL.
;(n-2)/2
sub ebx,2
shr ebx,1
To calculate f(n-1)*2 you need to use SHL in stead of SHR.
;(n-1)*2
dec ebx
shl ebx,1
Why don't you simplify the code? (You don't need the code at ReturnFib.)
; if ((n == 1) || (n == 2)) return 1;
mov eax, 1 ;less than 3 so result is 1, no need to calculate Fibonacci
cmp ebx, 2
jle Quit
valid:
EDIT
Here's how it looks for the first term.
;f(n-2)/2
sub ebx,2
push ebx ; store the number
call fib ; calculate n-2
shr eax,1
push eax ;store it away