Skip to content

Instantly share code, notes, and snippets.

@przemoc
Created July 19, 2010 14:06
Show Gist options
  • Save przemoc/481446 to your computer and use it in GitHub Desktop.
Save przemoc/481446 to your computer and use it in GitHub Desktop.
Fibonacci n-th number (modulo 2^32) in x86 assembler
; 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
@paulfurber
Copy link

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: 
...

@przemoc
Copy link
Author

przemoc commented Dec 19, 2013

@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