144,534 views
0 votes
0 votes
7. Implement a function factorial in RISC-V that has a single integer parameter n and returns n!. A stub of this function can be found in the file factorial.s. You will only need to add instructions under the factorial label, and the argument that is passed into the function is configured to be located at the label n. You may solve this problem using either recursion or iteration

User Sarwar Erfan
by
2.7k points

1 Answer

3 votes
3 votes

Answer:

addi x31, x0, 4

addi x30, x0, 2

Step-by-step explanation:

Recursion in computer sciencs is defined as a method of solving a problem in which the solution to the problem depends on solutions to smaller cases of the same problem. Such problems can generally be solved by iteration, but this needs to identify and index the smaller cases at time of programming.

addi x31, x0, 4

addi x30, x0, 2

addi x2, x0, 1600 // initialize the stack to 1600, x2= stackpointer

ecall x5, x0, 5 // read the input to x5

jal x1, rec_func

ecall x0, x10, 2 // print the result now

beq x0, x0, end

rec_func:

addi x2, x2, -8 // make room in stack

sd x1, 0(x2) // store pointer and result in stack

bge x5, x31, true // if i > 3, then go to true branch

ld x1, 0(x2)

addi x10, x0, 1 // if i <= 3, then return 1

addi x2, x2, 8 // reset stack point

jalr x0, 0(x1)

true:

addi x5, x5, -2 // compute i-2

jal x1, rec_func // call recursive func for i-2

ld x1, 0(x2) // load the return address

addi x2, x2, 8 // reset stack point

mul x10, x10, x30 // multiply by 2

addi x10, x10, 1 // add 1

jalr x0, 0(x1) // return

end:

User Edwidge
by
3.4k points