# How can I complete this mmix code to calculate Factorial?

948 views

### How can I complete this mmix code to calculate Factorial?

I'm new in using mmix editor (we have to use it in the University) and now we have to complete this code to get the Factorial of the input , so the code is

``````                LOC     Data_Segment
GREG    @
RESULT          OCTA    0
INPUT           OCTA    13

LOC     #100
result          IS      \$0
input           IS      \$1

Main            LDO     input,INPUT
PUSHJ   result,Factorial
STO     result,RESULT
End             TRAP    0,Halt,0

PREFIX  :Factorial:
inout           IS      \$0
[...]
:Factorial      [...]
End             POP     1,0
``````

we have to complete just the [...] but it doesn't work . So I had to make some edites to get the right answer like this :

``````                LOC     Data_Segment
GREG    @
RESULT          OCTA    0
INPUT           OCTA    13

LOC     #100
result          IS      \$0
input           IS      \$1
count           IS      \$2
Main            LDO     input,INPUT
LDO     count,INPUT
SET     result+1,input
SET     result+2,count
PUSHJ   result,Factorial
STO     result,RESULT
End             TRAP    0,Halt,0

PREFIX  :Factorial:
inout           IS      \$0
count           IS      \$1
test            IS      \$2
:Factorial      SUB     count,count,1
MUL     inout,inout,count
CMP     test,count,1
BZ      test,End
JMP     :Factorial
End             POP     1,0
``````

Now the next step is to use Sub-routine instead of the (MUL inout,inout,count) . And here what I did :

``````                LOC     Data_Segment
GREG    @
RESULT          OCTA    0
INPUT           OCTA    5

LOC     #100
result          IS      \$0
input           IS      \$1
count           IS      \$2
Main            LDO     input,INPUT
LDO     count,INPUT
SET     result+1,input
SET     result+2,count
PUSHJ   result,Factorial
STO     result,RESULT
End             TRAP    0,Halt,0

PREFIX  :Factorial:
inout           IS      \$0
count           IS      \$1
test            IS      \$3
:Factorial      SET     inout+1,inout
SET     count+1,count
PUSHJ   inout,:Multiply
STO     inout,inout
CMP     test,count,1
BZ      test,End
JMP     :Factorial
End             POP     1,0

PREFIX  :Multiply:
inout2          IS      \$0
count2          IS      \$1
test2           IS      \$3
:Multiply       SUB     count2,count2,1
CMP     test2,count2,3
BZ      test2,EndMul
JMP     :Multiply
EndMul          POP     1,0
``````

But it gives me an infinite loop (because of the `count` variable).

How can I solve this? 