Factorial in MIPS Assembly

A very good example of recursion is when one needs to calculate a Factorial number. The following code is in C++ (high level):

1
2
3
4
5
6
int factorial(int n)
{
	if (n <= 1)
		return 1;
	return n * factorial(n - 1);
}

Now let’s implement the same function but in MIPS assembly language.

The following code is for calculating the Factorial of any given integer using recursion in MIPS assembly language:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
fact:
 
	slti $t0, $a0, 2	# if i < 2 (i.e i == 1)
	beq $t0, $zero, cont	# if i >= 2 go to cont
	addi $v0, $zero, 1	# else make the resturn value 1
 
	jr $ra
 
 
cont:
 
	# OPERATION 1: save into stack
 
	addi $sp, $sp, -8	# make space in the stack
	sw $ra, 0($sp)		# save the return address
	sw $a0, 4($sp)		# save the argument value
 
	# OPERATION 2: compute fact(n - 1)
 
	addi $a0, $a0, -1
	jal fact
 
	# OPERATION 3: restore from stack
 
	lw $ra, 0($sp)		# get old return address from stack
	lw $a0, 4($sp)		# get old argument value from stack
	addi $sp, $sp, 8	# return stack pointer to original value, thus erasing all values
 
	# OPERATION 4: finally n * fact(n - 1)
 
	mult $v0, $a0		# multiply n * fib(n - 1)
	mflo $v0		# gets the result of the multiplication from the low register
 
	jr $ra
0 Comments , ,

No comments yet.

Leave a Reply

Protected by WP Anti Spam