2 Replies - 2271 Views - Last Post: 24 April 2013 - 10:45 PM

#1 newGains  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 07-April 13

recursive GCD in MIPS

Posted 24 April 2013 - 06:27 PM

pretty new to programming in assembly but my assignment is to write a GCD program but my program works sometimes and sometimes it doesn't work. if i put the smaller number first then the larger number i don't get the correct GCD but if i do the opposite i get the right answer
example:
if i enter 209 then 2585 it says the GCD is 209, which is incorrect
but, if i enter 2585 then 209 it says the GCD is 11 which is correct
looking for some guidance on to why my program is working one way and not the other
here is my code:
# Lab 2 - GCD
#
	.data
A:	.word 0
B:	.word 0
Prompt:	.asciiz "Type integer for A, press ENTER. Type integer for B, press ENTER \n"
Result:	.asciiz "\nThe GCD is "

	.globl main
	.text
	
main:
	li $v0,4		# syscall to print String
	la $a0,Prompt		# load address of Prompt
	syscall			# print Prompt String
	
	li $v0,5		# syscall to read integer
	syscall			# read first intger
	move $a0,$v0		# move integer in $v0 to $a0
	
	li $v0,5		# syscall to read integer
	syscall			# read next integer
	move $a1,$v0		# move integer in $v0 to $a1
	
baseCase:
	bne $a1,$zero,recCase	# if $a1 != 0 branch to recCase
	li $v0,4		# syscall to print String
	la $a0,Result		# load address of Result
	syscall			# print result String
	
	lw $a0,A		# load A
	li $v0,1		# syscall to print integer
	syscall			# print A
	
	li $v0,10		# terminate prog running
	syscall			# return control to system
	
recCase:
	sub $sp,$sp,12		# push stack
	sw $ra,0($sp)		# save return address
	sw $a0,4($sp)		# save registers
	sw $a1,8($sp)		
	move $t0,$a1		# move $a1 to $t0
	rem $a1,$a0,$a1		# $a1 =  A%B
	sw $t0,A		# store A for output
	jal baseCase		# jump to baseCase
	
	lw $ra,0($sp)		# load main
	addi $sp,$sp,12		# 
	jr $ra			# return to main



Is This A Good Question/Topic? 0
  • +

Replies To: recursive GCD in MIPS

#2 GunnerInc  Icon User is offline

  • "Hurry up and wait"
  • member icon




Reputation: 858
  • View blog
  • Posts: 2,281
  • Joined: 28-March 11

Re: recursive GCD in MIPS

Posted 24 April 2013 - 06:43 PM

Moving to Assembly...
Was This Post Helpful? 0
  • +
  • -

#3 turboscrew  Icon User is offline

  • D.I.C Addict

Reputation: 100
  • View blog
  • Posts: 615
  • Joined: 03-April 12

Re: recursive GCD in MIPS

Posted 24 April 2013 - 10:45 PM

The easiest "hack" would be to check the parameters first and swap them if the first mumber is smaller. Then do what you do now.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1