Created
June 12, 2024 13:33
-
-
Save danilopiazza/a9272da24d7e7ba30ec7768a340f3a65 to your computer and use it in GitHub Desktop.
Tail-recursive Fibonacci sequence in x86-64 Assembly
This file contains hidden or 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
section .text | |
global fibonacci | |
fibonacci: | |
enter 0, 0 | |
mov rsi, 1 | |
mov rdx, 0 | |
call fibonacci_loop | |
leave | |
ret | |
fibonacci_loop: | |
cmp rdi, 0 | |
jle .base_case | |
.recursive_case: | |
; rsi, rdx = rsi + rdx, rsi | |
mov rax, rdx | |
mov rdx, rsi | |
add rsi, rax | |
; rdi-- | |
dec rdi | |
; tail call | |
jmp fibonacci_loop | |
.base_case: | |
mov rax, rdx | |
ret |
This file contains hidden or 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
#include <inttypes.h> | |
#include <stdint.h> | |
#include <stdio.h> | |
uint64_t fibonacci(uint64_t n); | |
int main() | |
{ | |
for (unsigned int i = 0; i < 10; i++) { | |
printf("fibonacci(%u) = %"PRIu64"\n", i, fibonacci(i)); | |
} | |
return 0; | |
} |
This file contains hidden or 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
all: a.out | |
%.o: %.asm | |
nasm -f elf64 -o $@ $< | |
a.out: fibonacci.o main.c | |
$(CC) *.o main.c | |
clean: | |
@rm -f *.o a.out | |
.PHONY: all clean |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment