I\'m implementing a simple single-cycle MIPS processor for a class, and the only operations we implemented are lw
, sw
, j
, addi
Multiplication is simply repeated addition, in the same manner that addition is repeated incrementing and exponentiation is repeated multiplication.
Hence you could write a function that multiplies two values as follows (pseudo-code, obviously, but using functions primitive enough for your specifications):
def mult (a, b):
result = 0
while a > 0:
result = result + b
a = a - 1
return result
That's only good for unsigned values as it stands but, since you're doing factorials, you probably don't need to concern yourself with negative numbers at all.
In any case, it should be relatively simple to adjust for signed values so, in the interests of completeness, you could use:
def mult (a, b):
# Handle either being zero.
if a == 0 or b == 0:
return 0
# Handle either or both being negative (may
# need sign change to result).
sign = 1
if a < 0:
a = -a
sign = -sign
if b < 0:
b = -b
sign = -sign
# Both now positive, make sure first is not larger (less loops).
if b < a:
temp = a
a = b
b = temp
# Multiply small-a by large-b.
result = 0
while a > 0:
result = result + b
a = a - 1
# Adjust sign if needed.
if sign == -1:
result = -result
# Et, voila.
return result