问题
My assignment is to write a program that calculates first seven values of fibonacci number sequence. the formula given is:
Fib(1) = 1, Fib(2) = 1, Fib(n) = Fib(n-1) + Fib(n-2)
I believe that is a function but I do not understand how to incorporate it into code. I need to place the values in EAX register. I am using MASM not that makes any difference. Any hints?
回答1:
I suspect that this is an academic assignment so I'm only going to partially answer the question.
The fibonacci sequence is formally defined for non-negative integers as follows:
F(n) = n | n < 2
= F(n - 1) + F(n - 2) | n >= 2
This gives:
n | F(n)
0 | 0
1 | 1
2 | 1
3 | 2
4 | 3
5 | 5
6 | 8
7 | 13
etc etc...
You can do it with just a few registers, let's identify them:
- Rn (the number of the requested fibonacci number)
- Rf1 (used to calculate fibonacci numbers)
- Rf2 (also used to calculate fibonacci numbers)
- Rx (the register to hold the return value. can overlap with any other register)
Rn is passed as the argument to the function. Rf1 shall start at 0, and Rf2 shall start at 1.
Here's what we do to get the answer, split up by routines:
Begin
- Initialize Rf1 to 0.
- Initialize Rf2 to 1.
- Continue to Loop.
Loop
- Subtract 2 from Rn.
- If Rn is less than 0, jump to Finish.
- Add Rf2 to Rf1, storing the result in Rf1.
- Add Rf1 to Rf2, storing the result in Rf2.
- Jump to Loop.
Finish
- If Rn AND 1 is false (implying that Rn is even) jump to FinishEven.
- Store Rf1 as the return value.
- Return.
FinishEven
- Store Rf2 as the return value.
- Return.
Tracing through for Rn = 5:
- Rf1 = 0
- Rf2 = 1
- Rn = Rn - 2 // Rn = 3
- Test Rn < 0 // false
- Rf1 = Rf1 + Rf2 // Rf1 = 0 + 1 = 1
- Rf2 = Rf1 + Rf2 // Rf2 = 1 + 1 = 2
- Unconditional Jump to Loop
- Rn = Rn - 2 // Rn = 1
- Test Rn < 0 // false
- Rf1 = Rf1 + Rf2 // Rf1 = 1 + 2 = 3
- Rf2 = Rf1 + Rf2 // Rf2 = 3 + 2 = 5
- Unconditional Jump to Loop
- Rn = Rn - 2 // Rn = -1
- Test Rn < 0 // true
- Jump to Finish
- Test Rn & 1 // true
- Rx = Rf2 // 5
Our table shows that F(5) = 5, so this is correct.
回答2:
TITLE Chapter 4 Exercise 6 (ch04_06.asm)
Comment !
Description: Write a program that uses a loop to calculate the first
seven values in the Fibonacci number sequence { 1,1,2,3,5,8,13 }.
Place each value in the EAX register and display it with a
call DumpRegs statement inside the loop.
Last update: 05/02/2002
!
INCLUDE Irvine32.inc
.code
main PROC
mov eax,1
call DumpRegs
mov ebx,0 ; initial setup
mov edx,1
mov ecx,6 ; count
L1:
mov eax,ebx ; eax = ebx + edx
add eax,edx
call DumpRegs ; display eax
mov ebx,edx
mov edx,eax
Loop L1
exit
main ENDP
END main
来源:https://stackoverflow.com/questions/12865984/x86-fibonacci-program