Mouad Meziani
Mouad Meziani

Reputation: 29

How to code factorial of an input with Recursivity in NASM x86

%include "asm_io.inc"



segment .data

segment .bss



segment .text

    global asm_main

asm_main:


    enter 0,0
    pusha



    call    read_int

    push eax
    call fak_rekursiv
    add esp, 4



    call print_int
    call print_nl

    


    popa
    mov eax, 0
    leave
    ret

fak_rekursiv:

    enter 4, 0
    pusha

    

    mov eax, [ebp + 8]

    

    cmp eax, 0
    je ergebnis_1


    cmp eax, 1
    je ergebnis_1

    

    

    mov ebx, eax
    dec ebx
    mul ebx
    push ebx
    call fak_rekursiv
    pop ebx


            

    ergebnis:
        mov [ebp - 4], eax
        

    ergebnis_1:

        mov [ebp - 4], dword 1 

    popa
    mov eax, [ebp - 4]
    leave
    ret

I am learning to code on NASM and I was trying to understand recursion through using coding factorial but I got confused quickly.
How can I use Recursion in NASM to code factorial algorithm?

Upvotes: 1

Views: 187

Answers (2)

vengy
vengy

Reputation: 2257

Not too familiar with NASM, but here's a MASM solution which calls the factorial function recursively.

factorial.asm

.386
.model flat, stdcall
option casemap :none

includelib \masm32\lib\msvcrt.lib
printf PROTO C, :VARARG

.data
fmt db "%u! = %u", 13, 10, 0  

.code

factorial proc
    cmp     eax, 0   ; Special-case to account for 0! = 1
    je      retone
    cmp     eax, 1
    je      retnow
    push    eax
    dec     eax
    call    factorial
    pop     edx
    imul    eax, edx ; eax = eax * edx 
    
retnow:
    ret
    
retone:
    mov     eax, 1
    ret    
factorial endp

main:   

    ; Loop from 0 to 12 (max) factorial for 32-bit code.
    mov     ebx, 0  
num:
    mov     eax, ebx
    call    factorial
    invoke  printf, OFFSET fmt, ebx, eax
    inc     ebx
    cmp     ebx,13   
    jne     num
    
    ret
end main

Displays all factorials from 0 to 12

0to12!

Upvotes: 1

PIRIQITI
PIRIQITI

Reputation: 139

actually I have coded up factorial just for fun earlier. And now I have dug through my files to find that code :) here you go, but it is more like a pseudo-code which I only stepped through debugger.

factorial:
    push    eax
    test    eax, 07FFFFFFEh
    jz      .exit
    dec     eax
    call    factorial
    mul     dword [esp]
.exit:
    pop     edx
    ret

put different values in eax and step through it in debugger.

Upvotes: 2

Related Questions