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

Time:01-17

%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?

CodePudding user response:

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.

CodePudding user response:

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

.const

NUM equ 7  ; <--- change here (max factorial is 12 for 32-bit code)

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

.code

factorial proc
    cmp     eax, 1
    je      retnow
    push    eax
    dec     eax
    call    factorial
    pop     ebx
    mul     ebx  ; The mul instruction is used to perform a multiplication. 
                 ; It multiplies EAX by EBX and stores the result in EAX.
    
retnow:
    ret
factorial endp

main:   
    mov     eax,NUM
    call    factorial

    invoke  printf, OFFSET fmt, NUM, eax

    ret
end main

It computes 7! and outputs the result 5040

fact

  • Related