ARM Assembly Program to Calculate Factorial of a Number
mov r1, #1; mov r2, #1; loop: mul r1, r1, r2; add r2, r2, #1; cmp r2, r0; ble loop where r0 holds the input and r1 the factorial result.Examples
How to Think About It
Algorithm
Code
.global _start
_start:
mov r0, #5 @ Input number (change as needed)
mov r1, #1 @ Result initialized to 1
mov r2, #1 @ Counter initialized to 1
loop:
mul r1, r1, r2 @ result = result * counter
add r2, r2, #1 @ counter = counter + 1
cmp r2, r0 @ compare counter and input
ble loop @ if counter <= input, repeat
@ Exit syscall to return result in r0 (for demonstration)
mov r0, r1 @ move factorial result to r0
mov r7, #1 @ syscall number for exit
svc #0 @ make syscall
Dry Run
Let's trace the factorial of 5 through the code.
Initialize registers
r0=5 (input), r1=1 (result), r2=1 (counter)
First loop iteration
r1 = 1 * 1 = 1; r2 = 1 + 1 = 2; compare 2 <= 5 (true)
Second loop iteration
r1 = 1 * 2 = 2; r2 = 2 + 1 = 3; compare 3 <= 5 (true)
Third loop iteration
r1 = 2 * 3 = 6; r2 = 3 + 1 = 4; compare 4 <= 5 (true)
Fourth loop iteration
r1 = 6 * 4 = 24; r2 = 4 + 1 = 5; compare 5 <= 5 (true)
Fifth loop iteration
r1 = 24 * 5 = 120; r2 = 5 + 1 = 6; compare 6 <= 5 (false), exit loop
| Counter (r2) | Result (r1) |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 6 |
| 4 | 24 |
| 5 | 120 |
Why This Works
Step 1: Initialize registers
We set r0 to the input number, r1 to 1 for the factorial result, and r2 to 1 as the multiplier counter.
Step 2: Multiply and increment
Inside the loop, multiply r1 by r2 to accumulate the factorial, then increase r2 by 1.
Step 3: Loop control
Compare r2 with the input r0; if r2 is less or equal, repeat the loop to continue multiplying.
Step 4: Return result
When the counter exceeds the input, the loop ends and r1 holds the factorial result.
Alternative Approaches
.global _start
_start:
mov r0, #5 @ Input number
bl factorial
mov r7, #1 @ exit syscall
svc #0
factorial:
cmp r0, #1
ble end_factorial
push {r0, lr}
sub r0, r0, #1
bl factorial
pop {r1, lr}
mul r0, r0, r1
bx lr
end_factorial:
mov r0, #1
bx lr
.global _start
_start:
mov r0, #5 @ Input number
mov r1, #1 @ Result
loop:
mul r1, r1, r0
subs r0, r0, #1
bne loop
mov r0, r1
mov r7, #1
svc #0
Complexity: O(n) time, O(1) space
Time Complexity
The program loops from 1 to n, performing one multiplication per iteration, so time grows linearly with input size.
Space Complexity
Uses a fixed number of registers, so space is constant regardless of input size.
Which Approach is Fastest?
The iterative loop approach is fastest and simplest; recursion adds overhead and uses stack memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative loop | O(n) | O(1) | Simple and efficient factorial calculation |
| Recursive function | O(n) | O(n) | Demonstrating recursion but less efficient |
| Decrementing loop | O(n) | O(1) | Alternative loop style, modifies input register |