Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Non-Recursive Factorial Procedure

Status
Not open for further replies.

0x4B47

Programmer
Jun 22, 2003
60
0
0
US
Hi Assemblers,
After implementing a non recursive method a find the factorial of a given positive integer n, I thought it worked fine until I reached number 13. Up to 12! (12 factorial) I get all the correct answers, but 13! gives me 1932053504 when its supposed to be 6227020800. What I've realised here is that after EAX has reached its maximum highest integer (4,294,967,295) its clocked round, ie 4294967295 + 1932053504 = 6227020799.
What I am doing is storing the value whose factorial is to be calculated in a variable. Then I move that variable into EAX and ECX. Then I decrement the value in ECX. Then I use a loop which multiplies the value in ECX to EAX. Now from my understanding the product of a multiplication should be stored like this: EDX:EAX, correct?
Now obviously 6227020800 is too large to be stored in EAX alone, but after the multiplication EDX = 0!! How? From the code snippet below, can anyone spot my mistake?
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Code:
Factorial proc
   mov eax, factor
   mov ecx, factor
   dec ecx
L1:
   mul ecx
Loop L1

CalcResult:
   cmp edx, 0
   je EAXAns
   push eax
   mov eax, edx
   call WriteDec
   pop eax
EAXAns:
   call WriteDec
   call Crlf
   ret
Factorial endp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Any help will be appreciated.
Kunal.
 
Because you loop downwards, not upwards. The last multiplication is by 1, which obviously doesn't create an overflow into edx, but overwrites edx, which had an overflow on the previous multiplication.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top