On this page
Factorial Calculation
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
| |
Explanation
Algorithm
Initialization
- CX = 4 (calculate 4!)
- AX = 1 (initial result)
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
Store Result
- MOV [2000H], AX: Store final result in memory
Execution Trace for 4!
| Iteration | BX (Before INC) | BX (After INC) | AX (After MUL) | Continue? |
|---|---|---|---|---|
| 1 | 1 | 2 | 1 × 2 = 2 | Yes |
| 2 | 2 | 3 | 2 × 3 = 6 | Yes |
| 3 | 6 | 7 | 6 × 7 = 42 | No (Wait!) |
Note: There’s a logic issue in this code. It should compare with the loop counter differently.
Corrected Version
| |
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
| |