# Factorial Infinite Loop Problem (MIPS)

Page 1 of 1

## 1 Replies - 1940 Views - Last Post: 17 April 2013 - 03:24 PM

### #1 mangobyebye

Reputation: 0
• Posts: 1
• Joined: 17-April 13

# Factorial Infinite Loop Problem (MIPS)

Posted 17 April 2013 - 03:22 PM

Hello,

I have been tasked with writing a simlple calculator, and one of the functions it must complete is to compute the binomial coefficient (nchoosek) of two numbers. I have posted (hopefully) all relevant code that I have written so far. My problem is that the 'factorial' function seems to endlessly loop and I cannot for the life of me figure out why!

My end goal is to be able to save the result of the calculation of the binomial coefficient into register \$s0. Any help would be greatly appreciated!

I have attached my full source code in case it is of any assistance.

```calnchoosek:

##### SAVE TO STACK #####
addi \$sp, \$sp, -4	# Decrement stack pointer by 16
sw \$ra, 0(\$sp)		# Save return address to stack

##### C(n,k) = n!/((n-k)! k!) #####
#
#     Where x = n-k
mtc1 \$s6, \$f2		# \$f2 = n
mtc1 \$s5, \$f3		# \$f3 = k
sub.s \$f4, \$f2, \$f3	# \$f4 = x

##### For n! #####
mov.s \$f12, \$f2		# \$f12 = n
l.s \$f13, fl_pos_one	# init \$f13 to 1

addi \$sp, \$sp, -4	# make room on the stack
sw \$ra, 0(\$sp)		# preserve the return address

jal factorial

lw \$ra, 0(\$sp)		# return the return address
addi \$sp, \$sp, 4	# restore the stack pointer

mov.s \$f5, \$f0		# \$f5 = n!

##### For k! #####
mov.s \$f12, \$f3		# \$f12 = k
l.s \$f13, fl_pos_one	# init \$f13 to 1

addi \$sp, \$sp, -4	# make room on the stack
sw \$ra, 0(\$sp)		# preserve the return address

jal factorial

lw \$ra, 0(\$sp)		# return the return address
addi \$sp, \$sp, 4	# restore the stack pointer

mov.s \$f6, \$f0		# \$f6 = k!

##### For x! #####
mov.s \$f12, \$f4		# \$f12 = x
l.s \$f13, fl_pos_one	# init \$f13 to 1

addi \$sp, \$sp, -4	# make room on the stack
sw \$ra, 0(\$sp)		# preserve the return address

jal factorial

lw \$ra, 0(\$sp)		# return the return address
addi \$sp, \$sp, 4	# restore the stack pointer

mov.s \$f7, \$f0		# \$f7 = x!

##### Final calculations #####
##### Answer = \$f5/(\$f7 * \$f6)

mul.s \$f8, \$f7, \$f6
div.s \$f10, \$f5, \$f8

mov.s \$f0, \$f10
mfc1 \$s6, \$f0

jr \$ra

factorial:
l.s \$f15, fl_pos_one		# \$f2 = 1
c.eq.s \$f15, \$f12		# Check if \$f12 = 1
bc1t f_end				# If true, branch to f_end

mul.s \$f13, \$f12, \$f13	# \$f13 = \$f12 * \$f13
l.s \$f14, fl_neg_one
add.s \$f12, \$f12, \$f14	# Decrement \$f12
b factorial				# repeat

f_end:
mov.s \$f0, \$f13		# save intermediate value to

jr \$ra				# return
```

Is This A Good Question/Topic? 0

## Replies To: Factorial Infinite Loop Problem (MIPS)

### #2 GunnerInc

• "Hurry up and wait"

Reputation: 900
• Posts: 2,339
• Joined: 28-March 11

## Re: Factorial Infinite Loop Problem (MIPS)

Posted 17 April 2013 - 03:24 PM

Moved to Assembly...