Created
July 19, 2010 14:06
-
-
Save przemoc/481446 to your computer and use it in GitHub Desktop.
Fibonacci n-th number (modulo 2^32) in x86 assembler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; Fibonacci n-th number (modulo 2^32) | |
; | |
; input: | |
; ecx = n | |
; modifies: | |
; eax, ecx, edx | |
; ouput: | |
; eax = number | |
; size: | |
; 15 bytes | |
use32 | |
_fibonacci: | |
xor eax, eax ; 31 c0 | |
jecxz _fibonacci_end ; e3 0a | |
dec ecx ; 49 | |
inc eax ; 40 | |
jecxz _fibonacci_end ; e3 06 | |
cdq ; 99 | |
_fibonacci_loop: | |
xchg eax, edx ; 92 | |
add eax, edx ; 01 d0 | |
loop _fibonacci_loop ; e2 fb | |
_fibonacci_end: | |
ret ; c3 |
And here's a version using the same formula but runs in linear time :) :
_start:
fld tword [sqrt5]
fld tword [n]
fld tword [phi]
fyl2x
fld st0
frndint
fsub st1, st0
fxch st1
f2xm1
fld1
fadd
fscale
fdiv st2
fistp qword [result]
Exit:
...
@paulfurber: Thanks for providing FP versions! They're not as short as I would like them to be, though. :>
Anyway, I'm not FP guy myself, so I won't fiddle with squeezing it as much as possible (please forgive my rude assumption that it is possible), but others are free to do so in the comments!
And sorry for late reply, but unfortunately gists lacks any notification system...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, I got inspired by this to write a similar function using floating point and the phi formula for finding the nth Fibonacci. ecx is the number and it uses the formula round(phi^n / sqrt(5)) to do it where phi is 1+sqrt(5)/2. Not nearly as small as yours but quite quick: