Last active
December 13, 2020 08:26
-
-
Save seisvelas/1e798ccee2372a5ea6138e0285f579cb to your computer and use it in GitHub Desktop.
x64 implementation of the f(n)=f(n-1)+f(n-2) fibonacci algorithm
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
global fibonacci | |
extern printf | |
fibonacci: | |
xor rax, rax | |
; f(n = 1|0) = n | |
cmp rdi, 1 | |
jle identity | |
; f(n > 1) = f(n - 1) + f(n - 2) | |
; [rsp] = f(n-1) | |
push rdi | |
dec rdi | |
call fibonacci | |
pop rdi | |
; rax = [rsp] + f(n-2) | |
push rax | |
push rdi | |
sub rdi, 2 | |
call fibonacci | |
pop rdi | |
add rax, [rsp] | |
; realign stack | |
add rsp, 8 | |
jmp return | |
identity: | |
mov rax, rdi | |
return: | |
ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I got very stuck on this because I was realigning the stack via
sub rsp, 1
which failed becauseThis was so hard. Well, it took less than an hour, but relative to my expectations coming from high level languages, where this is so simple. I should implement this in C (where it is super easy) and see asm output without optimizations - I'm curious how a compiler would do this.
Okay, will study this later