This program calculates the factorial of a number using iterative multiplication.

Description

The program computes n! (factorial of n) by multiplying successive numbers from 1 to n. The example calculates 4! = 1 × 2 × 3 × 4 = 24.

Registers Used

  • CX: Target number (n)
  • AX: Accumulator for result
  • BX: Current multiplier

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
MOV CX,04H ; factorial of 4
MOV AX,0001H

HERE: 
	MOV BX,AX
	INC BX
	MUL BX
	CMP BX,CX
	JNZ HERE
	MOV [2000H] , AX
HLT

Explanation

Algorithm

  1. Initialization

    • CX = 4 (calculate 4!)
    • AX = 1 (initial result)
  2. Factorial Loop

    • MOV BX, AX: Copy current result to BX
    • INC BX: Increment to get next multiplier
    • MUL BX: Multiply AX by BX (AX = AX × BX)
    • CMP BX, CX: Check if we’ve reached n
    • JNZ HERE: Continue if not done
  3. Store Result

    • MOV [2000H], AX: Store final result in memory

Execution Trace for 4!

IterationBX (Before INC)BX (After INC)AX (After MUL)Continue?
1121 × 2 = 2Yes
2232 × 3 = 6Yes
3676 × 7 = 42No (Wait!)

Note: There’s a logic issue in this code. It should compare with the loop counter differently.

Corrected Version

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
MOV CX, 04H      ; factorial of 4
MOV AX, 0001H    ; result = 1
MOV BX, 0001H    ; counter = 1

HERE: 
    INC BX       ; next number
    MUL BX       ; result *= next number
    CMP BX, CX   ; reached n?
    JNZ HERE     ; continue if not
    MOV [2000H], AX
HLT

Result

  • 4! = 1 × 2 × 3 × 4 = 24 (18H)
  • Stored at memory location 2000H

Limitations

  • Maximum factorial for 16-bit: 8! = 40320 (fits in AX)
  • For 9! and above, result exceeds 16 bits (need DX:AX)

For Larger Factorials

1
2
3
4
; For 32-bit result (factorial up to 12)
MUL BX    ; Result in DX:AX (32-bit)
; DX = higher 16 bits
; AX = lower 16 bits