Reputation: 1553
I am currently in the process of learning MASM, and I've faced the following task:
Write a program that will calculate the value of f(n) according to the following recursive formula: f(n) = f(n-1) + 2*f(n-2) -2, f(0) = 0, f(1) = 3
I'm calculating for n = 15
and since I know f(0)
, f(1)
I subtract two from n
's value.
TITLE Recursion Solver
INCLUDE Irvine32.inc
.data
n SDWORD 15 ;
n2 SDWORD 0 ; n-2 (n0)
n1 SDWORD 3 ; n-1 (n1)
.code
main PROC
mov ecx, n ; initialize loop counter
sub ecx, 2 ;
again:
mov eax, n1 ; eax = f(n-1)
mov ebx, n2 ; ebx = f(n-2)
add ebx, ebx ; ebx = 2*f(n-2)
sub ebx, 2 ; ebx = 2*f(n-2) - 2
add eax, ebx ; eax = f(n-1) + 2*f(n-2) -2
mov ebx, n2 ;
mov n2, eax ;
mov n1, ebx ;
loop again
call WriteInt
exit
main ENDP
END main
I wrote a simple C++ program to calculate the n
'th value according to the formula, but for some reason the assembly program isn't working as expected.
Here's the output of my C++ program:
f(0) = 0
f(1) = 3
f(2) = 1
f(3) = 5
f(4) = 5
f(5) = 13
f(6) = 21
f(7) = 45
f(8) = 85
f(9) = 173
f(10) = 341
f(11) = 685
f(12) = 1365
f(13) = 2733
f(14) = 5461
f(15) = 10925
and this is the integer the assembly outputs: -13859
Upvotes: 0
Views: 209
Reputation: 2952
There is one error that I can see. You mix f(n-1)
and f(n-2)
.
The easiest way to fix it is by changing the definition of starting point:
n1 SDWORD 3; n0
n2 SDWORD 0; n1
But of course you can swap all references to these variables in your code.
And the second error that I found:
mov ebx, n1 ;
mov n1, eax ;
mov n2, ebx ;
Upvotes: 1