How to resolve the algorithm Factorial step by step in the x86 Assembly programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Factorial step by step in the x86 Assembly programming language

Table of Contents

Problem Statement

Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Factorial step by step in the x86 Assembly programming language

Source code in the x86 programming language

global factorial
section .text

; Input in ECX register (greater than 0!)
; Output in EAX register
factorial:
  mov   eax, 1
.factor:
  mul   ecx
  loop  .factor
  ret

global fact
section .text

; Input and output in EAX register
fact:
  cmp    eax, 1
  je    .done   ; if eax == 1 goto done

  ; inductive case
  push  eax  ; save n (ie. what EAX is)
  dec   eax  ; n - 1
  call  fact ; fact(n - 1)
  pop   ebx  ; fetch old n
  mul   ebx  ; multiplies EAX with EBX, ie. n * fac(n - 1)
  ret

.done:
  ; base case: return 1
  mov   eax, 1
  ret

global factorial
section .text

; Input in ECX register
; Output in EAX register
factorial:
  mov   eax, 1  ; default argument, store 1 in accumulator

.base_case:
  test  ecx, ecx
  jnz   .inductive_case  ; return accumulator if n == 0
  ret

.inductive_case:
  mul   ecx         ; accumulator *= n
  dec   ecx         ; n -= 1
  jmp   .base_case  ; tail call

  

You may also check:How to resolve the algorithm Attractive numbers step by step in the Raku programming language
You may also check:How to resolve the algorithm Start from a main routine step by step in the Nim programming language
You may also check:How to resolve the algorithm Anagrams/Deranged anagrams step by step in the REXX programming language
You may also check:How to resolve the algorithm Hickerson series of almost integers step by step in the REXX programming language
You may also check:How to resolve the algorithm XML/DOM serialization step by step in the Lasso programming language