我为一个类实现了一个简单的单周期MIPS处理器,我们实现的唯一操作是lw
,sw
,j
,addi
,or
,and
,add
,
sub
,beq
,slt
,jr
,andi
,jal
,bne
和sll
。我必须编写一个测试阶乘函数的MIPS文件。显然,我无法使用尚未实施的指令,但由于因子意味着:result = n * factorial(n-1)
,我需要一种方法来乘以两个值。有没有办法用前面提到的说明做到这一点?
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
答案 0 :(得分:1)
乘法只是重复加法,与加法重复递增的方式相同,并且取幂重复乘法。
因此,您可以编写一个函数,将两个值相乘如下(显然,伪代码,但使用的函数原语足以满足您的规范):
def mult (a, b):
result = 0
while a > 0:
result = result + b
a = a - 1
return result
这对于无符号值只有好处,但是,既然你做了阶乘,你可能根本不需要来关注自己的负数
在任何情况下,调整签名值都应该相对简单,因此,为了完整起见,您可以使用:
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