Question

I am trying to create an assembly program that calculates the factorial of a number:

.data
n dword 1
res dword 1

.code
start:
mov ecx, 5
Top:
add n, 1
mov eax, res
mov ebx, n
mul eax, ebx
mov res, eax
dec ecx
jnz Top

Next:
Invoke crt_printf, addr res

The error I am encountering with the codes above is the mul part, where I want to multiply eax and ebx. How can I fix this? Any help is much appreciated.

Was it helpful?

Solution

You want

mul ebx

The eax is implicit. What mul ebx does is ebx*eax and stores the result in edx:eax (the higher order bits go in edx when eax is not big enough to hold the result, in your example this is not a problem though).

Note that you have two parallel counters in n and ecx. You can get rid of one to make your code shorter:

.code
start:
mov ecx, 5
mov eax, 1
Top:
mul ecx
dec ecx
jnz Top
mov res, eax

Even shorter, you can replace the two lines dec ecx, jnz Top by loop Top. Now that's some short and sweet factorial function!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top