3
1) One way to calculate the square of a number
x
to add all the odd numbers from 1 to 2
x
-1.
So
x² = (2x-1) + (2x-3) + .
.. + 3 + 1.
For example, 4² = 7 + 5 + 3 + 1 = 16.
Here is a recursive
procedure to calculate the square of a number in C:
Corrections below in blue.
int square (int x) {
if (x == 0) {
return 0;
} else if (x < 0) {
return square (-x);
} else {
return ((2*x – 1) + square (x - 1));
}
}
Here is a translation of the above program into MIPS assembly language (assume no branch
delay slot):
square:
addi $v0, $zero, 0
; if a0 = 0, return 0
beq
$a0, $zero, exit
; Don’t really need recursive call for second clause!
slt
$t0, $a0, $zero
beq
$t0, $zero, notless
; if a0 < zero jump ahead
sub
$a0, $zero, $a0
notless: addi $sp, $sp,
-8
sw
$s0, 4($sp)
sw
$ra, 8($sp)
; store $ra on stack, do NOT
; use offset 0 off of $sp
; by MIPS convention
add $t0, $a0, $a0
addi $s0, $t0, -1
addi $a0, $a0, -1
jal square
add
$v0, $v0, $s0
lw
$s0, 4($sp)
lw
$s0, 4($sp)
; restore s0, ra from stack
lw
$ra, 8($sp)
addi $sp, $sp,
-8
exit:
jr
$ra
; don’t touch sp if a0 = 0