C code
int GCD(int m, int n)
{ //Call MACRO PRINTARGS as the first line of code in GCD
//PRINTARGS($a0, $a1)
int result = 0;
// Base Case:
if(m == n)
result = m;
else if (m > n)
// Recursive Case:
result = GCD(m-n, n);
else
// Recursive Case:
result = GCD(m, n-m);
//Call MACRO PRINTARGS as the last line of code in GCD before jr $ra
//PRINTARGS($a0, $a1)
return result;
}
GCD:
my function will go infinite loop if the first argument is large than second argument
(Except the case m=2, n=1)
$a2 is m
$a3 is n
$v1 is where i store the result
The Greatest Common Denominator (GCD) is the largest positive integer that divides the two
numbers without a remainder.
(PRINTARGS is just a function i wrote to print the value of m and n every time it runs the loop)
GCD:
PRINTARGS($a2,$a3)
addi $sp $sp,-4
sw $ra 0($sp)
lb $a0,newline
li $v0,11
syscall #print new line
li $v1,0 # result = 0 result = v1
#base case
bne $a2,$a3,else2 #if m!=n, go to else2
move $v1,$a2 #move value m to v1
j GCD_DONE #jump to GCD_DONE
#Recursive Case: else if (m > n), result = GCD(m-n, n);
else2:
blt $a2,$a3,else3 #if m >n jump to else 3
sub $a2,$a2,$a3 #m-n
jal GCD
else3:
#Recursive Case: result = GCD(m, n-m);
sub $a3,$a3,$a2 #n-m
jal GCD
PRINTARGS($a2,$a3)
GCD_DONE:
addi $sp $sp,4
lw $ra 0($sp)
jr $ra