Question

I am trying to find the GCD of two numbers with recursion. This code is what I've done so far but apparently it gets into an infinite loop and i can't understand why and how to solve this problem. I would appreciate some help

.data
string1: .asciiz "Enter the first number:  "
string2: .asciiz "Enter the second number:  "
string3: .asciiz "GCD is : "

.text

li $v0,4
la $a0,string1
syscall

li $v0, 5
syscall
add $s0,$v0,$zero  #s0 = first number

li $v0,4
la $a0,string2
syscall

li $v0, 5
syscall
add $s1,$v0,$zero   #s1= second number




slt $t0,$s0,$s1
beq $t0,$zero,L    # if first number < second number , swap
add $t1,$s0,$zero
add $s0,$s1,$zero
add $s1,$t1,$zero

L: 
add $a0,$s0,$zero   # put first number in $a0 as input argument
add $a1,$s1,$zero   # put second number in $a1 as input argument



jal GCD

GCD:

addi $sp,$sp,-4
sw $ra,0($sp)


bne $a1,$zero,L1  # base case condition

add $v0,$zero,$a0  # if base case is true
addi $sp,$sp,4
jr $ra


L1:
div $a0,$a1
add $a0,$a1,$zero
mfhi $a1
jal GCD


lw $ra,0($sp)
addi $sp,$sp,4

jr $ra


add $s3,$v0,$zero  # put result in $s3


li $v0,4
la $a0,string3
syscall


li $v0,1
add $a0,$s3,$zero
syscall
Was it helpful?

Solution

So your program starts execution at the beginning of the .text segment and continues straight onto the line jal GCD after the L label.

Next your program jumps to the GCD label where it executes until the jr $ra which makes it return to the jal which has as its next instruction of course GCD. This causes the infinite loop.

So the problem here is that you have inserted the GCD function in the middle of your main function. Generally speaking it is always an error to jal to the next line.

So you should move the definition of GCD elsewhere and consider what it is that you would like to run after returning from this function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top