• 0

[asm]


Question

I can't for the life of me figure out how to calculate the fibonacci series in asm, heres what I have, whish doesnt work properly. Any advice?

INCLUDE Irvine32.inc

.data

count1 word 1
count2 word 1
count3 word ?

.code
main PROC

	mov ax, 0
	mov ecx, 8


L1:  
	mov ax, count1
	mov bx, count2
	add ax, bx
	call DumpRegs
	mov count1,ax


loop L1

	exit


main ENDP
END main

Link to comment
Share on other sites

4 answers to this question

Recommended Posts

  • 0

Well... one advice that i have...

Use CMP and the JMP-instructions. The LOOP instruction is slower... it's also recommended to use the native width of the registers. So if it's a 32-bit processor then use 32-bit registers.

Link to comment
Share on other sites

  • 0

I'm not sure what assembler you're using, but the main idea is the same either way, so you can change it to fit your assembler.

Here is how I would do it:

; requestNum is the number from the fibonacci series that is requested
; returnNum is the number we will return

; first compare with the first 3 numbers in the series since we skip them in the loop
mov eax, requestedNum 
cmp eax, 3
; if eax < 3
jl nless
; else if eax == 3
je neq
; else
jmp nstart

nless:
; if we're here, that means requestNum < 3, therefore the fibonacci number is 1
mov returnNum, 1
jmp done

neq:
; if we're here, that means requestNum = 3, therefore the fibonacci number is 2
mov returnNum, 2
jmp done

nstart:
; now we compute the rest of the series based on the first few
; initialize the first 3 fibonacci numbers
mov eax, 1
mov ebx, 1
mov ecx, 2
; this is the loop counting variable, we start from 3 until requestNum
mov edx, 3
jmp loop0

loop0:
cmp edx, requestNum
jge loop0done
mov eax, ebx
mov ebx, ecx
; now add the two together
mov ecx, eax
add ecx, ebx
inc edx
jmp loop0

loop0done:
mov returnNum, ecx
jmp done

done:
; when we get here, 'returnNum' will contain the resulting fibonacci number
exit

I commented it a lot so it's clear, but if it's not, let me know :)

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.