Skip to content

Instantly share code, notes, and snippets.

@ncdulo
Last active February 28, 2020 21:03
Show Gist options
  • Save ncdulo/e49355b046b874bbf469b632cb1f073d to your computer and use it in GitHub Desktop.
Save ncdulo/e49355b046b874bbf469b632cb1f073d to your computer and use it in GitHub Desktop.
Recursive Factorial (x86_64 ASM + C)
/*
* An application that illustrates calling the factorial function defined in 'factorial.asm'
* https://cs.lmu.edu/~ray/notes/nasmtutorial/
*
* To build & run:
* nasm -f elf64 factorial.asm && gcc -std=c99 -o factorial2 factorial.o callfactorial.c
*/
#include <stdio.h>
#include <inttypes.h>
uint64_t factorial (uint64_t);
int main() {
for (uint64_t i = 0; i < 20; i++) {
printf("factorial(%2lu) = %lu\n", i, factorial(i));
}
return 0;
}
; An implementation of the recursive function:
;
; uint64_t factorial(uint64_t n) {
; return (n <= 1) ? 1 : n * factorial(n-1);
; }
;
; C is used to provide a wrapper and make calling this function in a loop a bit less painful.
; This requires GCC, NASM, and a 64-bit processor. This will most likely *only* work on Linux
; https://cs.lmu.edu/~ray/notes/nasmtutorial/
;
; To build & run:
; nasm -f elf64 factorial.asm && gcc -std=c99 -o factorial2 factorial.o callfactorial.c
GLOBAL factorial
section .text
factorial:
cmp rdi, 1 ; n <= 1?
jnbe L1 ; if not, do a recursive call
mov rax, 1 ; otherwise return 1
ret
L1:
push rdi ; save n on stack (also aligns %rsp)
dec rdi ; n - 1
call factorial ; factorial(n-1), result goes in %rax
pop rdi ; restore n
imul rax, rdi ; n * factorial(n-1), stored in %rax
ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment