L12-Computing Factorial ECE 2560 L12-Computing Factorial Department of Electrical and Computer Engineering The Ohio State University ECE 3561 - Lecture 1
HLL to Assembler Pseudo HLL HLL structure Their flow chart HHL code Corresponding Assembler ECE 3561 - Lecture 1
Computing n! What is n! ? This can be done recursively n factorial is n*(n-1)*(n-2)*…(1) n! = n*(n-1)! This can be done recursively Have a subroutine to compute n! In the computation is n=1 then result is 1 If n>1 then the value is n*(n-1)! And to compute (n-1)! the routine called again ECE 3561 - Lecture 1
Pseudocode Factorial – n! function nfact (var n) return z; if (n=1) then z = 1; else z = n * nfact(n-1); end if; end nfact; ECE 3561 - Lecture 1
Features of recursive routines Can have no local data that could be modified in the recursive call Data needs to be on the stack Any register used must be restored before the routine returns. Because there is no local data and no absolute addresses the routine is also “position independent” Position independent – code that can be run in any location in memory. ECE 3561 - Lecture 1
Factorial - recursion Arguments will be passed on the stack. The number n to find n! of is pushed on TOS Result is returned on the stack. The value of n! is returned on the TOS ECE 3561 - Lecture 1
The routine N is passed on the stack so the stack looks like this when entering routine So start by saving the state of the processor ECE 3561 - Lecture 1
The code fact push SR ;save state push R5 push R6 push R7 mov 10(SP),R5 ;get n cmp #1,R5 jeq rtnval dec R5 ;R5=n-1 call fact ;compute n-1! ECE 3561 - Lecture 1
On Recursive call The stack will look like this Now what happens when you start to return with values? ECE 3561 - Lecture 1
Result - on the stack Point size is very small – look at it in word Result is on the stack and at the top of the stack. fact push SR ;save state push R5 push R6 push R7 mov 10(SP),R5 ;get n cmp #1,R5 jjeq rtnval dec R5 ;R5=n-1 call fact ;computer n-1! inc R5 ;R5 now n pop R6 ;n-1 fact to R6 push R6 call shmult ;stack has null then result pop R7 jmp cont rtnval mov #1,R7 cont mov R7,10(SP) ;put value of n! in rtn location pop R7 ;clean up things pop R6 pop R5 pop SR ret Point size is very small – look at it in word ECE 3561 - Lecture 1
Performance of code Code is an extensive use of stack and implementation of good coding practices. Passing arguments on stack Routines have no side effects ECE 3561 - Lecture 1
Extending to 32 bit result Factorial when result limited to 16 bits does not allow for much range for factorial. 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 In a 16-bit value 8! Is the largest that can be computed. Could 32-bits be used? ECE 3561 - Lecture 1
A look at the math The math ECE 3561 - Lecture 1