问题
I'm implementing a simple single-cycle MIPS processor for a class, and the only operations we implemented are lw
, sw
, j
, addi
, or
, and
, add
,
sub
, beq
, slt
, jr
, andi
, jal
, bne
and sll
. I have to write a MIPS file testing a factorial function. Obviously, I can't use instructions that haven't been implemented but since factorial means: result = n * factorial(n-1)
, I need a way to multiply two values. Is there a way to do that with the instructions mentioned earlier?
EDIT: I got it working! Here's my MIPS code:
multiply:
add $v1, $0, $0 # initialize result to 0
loop:
beq $a2, $0, done # if second operand reaches 0, the multiplication is over
add $v1, $v1, $a1 # result = result + first operand
addi $a2, $a2, -1 # decrements second operand
j loop # loops
done:
jr $ra # returns to caller
回答1:
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
来源:https://stackoverflow.com/questions/43646945/alternative-to-mul-mult-for-multiplication-in-assembly-mips