How to find the factorial of 5 using NASM?

Viewed 328

I have just started to learn NASM using tutorialspoint's online Asm Compiler (https://www.tutorialspoint.com/compile_assembly_online.php).

My first warmup is to write a code that calculates the factorial of 5. Here is my try:

section .text
    global _start      
_start:     
    mov eax, 1      ;a = 1
    mov ebx, 1      ;f = 1
    int 0x80        ;call kernel
    
l1:
    mul ebx        ; f = f*a
    inc eax        ; a++
    cmp eax, 5     ; if a<=5
    jle l1         ; jump to l1

section .data
msg db 'Factorial 5 is:',0xa    
len equ $ - msg 

It doesn't print any value out, can anyone give me a hint on what's the problem? Thank you.

1 Answers

I would not use the mul operation. In assembly you want to stick to simplicity and avoid division, multiplication and floating point unless you have no other choice.

5! = 5 * 4 * 3 * 2 = 5 * 3 * 2 * 2 * 2 = (5 * 2 + 5 ) * 2 * 2 * 2

So, to compute this:

5 << 1
ADD 5
<< 3

No looping or multiplication necessary. If you are going to use a loop (or if that is the point of the lesson), normally in assembly you compare to zero, so you count down, not up.

Using a debugger is essential in assembly. There are some structural issues with your code that stepping through with a debugger will reveal. You can't just use the online system alone. You have to set up a debugger on your computer.

Related