Question

Using SPIM, write and test a program that finds the Greatest Common Divisor of two integers...

  • Using SPIM, write and test a program that finds the Greatest Common Divisor of two integers using a recursive function that implements Euclid's GCD algorithm as described below. Your program should greet the user "Euclid's GCD algorithm", prompt the user to input two integers, and then output the result
  • "Euclid's Greatest Common Divisor Algorithm"
    GCD(M,N) = M                      (if N is 0)
    GCD(M,N) = GCD(N, M % N)   (if N > 0)
  • you may assume that inputs are non-negative
  • name your assembly language file
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Given below is the code for the question. Please do rate the answer if it helped. Thank you.

.data
   inMsg: .asciiz "Enter a number: "
   outMsg: .asciiz "GCD is "
.text

   #print string
   la $a0, inMsg
   li $v0, 4
   syscall
  
   #read int
   li $v0, 5
   syscall
   move $t0, $v0
  
  
   #print string
   la $a0, inMsg
   li $v0, 4
   syscall
  
   #read int
   li $v0, 5
   syscall
   move $t1, $v0
  
   #set up args and call function gcd
   move $a0, $t0
   move $a1, $t1
   jal gcd
   move $t0, $v0 #store result from v0 into t0
  
   #print string
   la $a0, outMsg
   li $v0, 4
   syscall
  
   #print int
   move $a0, $t0
   li $v0, 1
   syscall
  
   #exit
   li $v0, 10
   syscall
  

gcd:
   #save register on stack
   sub $sp, $sp, 12
   sw $ra, 0($sp)
   sw $a0, 4($sp)
   sw $a1, 8($sp)
  
   beqz $a1, base_case
   div $a0, $a1 #will leave remainder in HI
   move $a0, $a1 #set M =N for next recursive call
   mfhi $a1 #set N = remainder of division
   jal gcd
   b end_gcd
  
base_case:
   move $v0, $a0

end_gcd:
  
   #restore registers
   lw $ra, 0($sp)
   lw $a0, 4($sp)
   lw $a1, 8($sp)
   add $sp, $sp, 12
   jr $ra


output
---
Enter a number: 12
Enter a number: 15
GCD is 3
-- program is finished running --

Enter a number: 3
Enter a number: 5
GCD is 1
-- program is finished running --

Add a comment
Know the answer?
Add Answer to:
Using SPIM, write and test a program that finds the Greatest Common Divisor of two integers...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT