Math Examples

Mathematical computations in Romasm

Factorial

Calculate 5!

; Calculate factorial of 5
; 5! = 5 × 4 × 3 × 2 × 1 = 120
LOAD R0, 5       ; n = 5
LOAD R1, 1       ; result = 1
LOAD R2, 1       ; constant 1

factorial_loop:
    MUL R1, R0   ; result = result * n
    DEC R0       ; n = n - 1
    CMP R0, R2   ; Compare n with 1
    JGT factorial_loop  ; Continue if n > 1

PRINT R1         ; Output: 120

Power Function

Calculate 2^8

; Calculate 2^8 = 256
LOAD R0, 2       ; base = 2
LOAD R1, 8       ; exponent = 8
LOAD R2, 1       ; result = 1
LOAD R3, 1       ; constant 1

power_loop:
    MUL R2, R0   ; result = result * base
    DEC R1       ; exponent = exponent - 1
    CMP R1, R3   ; Compare exponent with 1
    JGT power_loop  ; Continue if exponent > 1

PRINT R2         ; Output: 256

Square Root (Newton's Method)

Calculate √25

; Square root using Newton's method
; x_{n+1} = (x_n + n/x_n) / 2
LOAD R0, 25000   ; n = 25.000 (scaled by 1000)
LOAD R1, 5000    ; x = 5.000 (initial guess, scaled)
LOAD R2, 2       ; constant 2
LOAD R3, 1000    ; scaling factor
LOAD R4, 10      ; iteration limit

sqrt_loop:
    ; Calculate n/x
    LOAD R5, R0
    DIV R5, R1    ; R5 = n/x
    
    ; Calculate (x + n/x)
    ADD R1, R5    ; R1 = x + n/x
    
    ; Divide by 2
    DIV R1, R2    ; R1 = (x + n/x) / 2
    
    DEC R4
    CMP R4, 0
    JGT sqrt_loop

PRINT R1         ; Output: ~5000 (5.000)

Using Standard Library

Calculate sin(30°) using stdlib

; Calculate sin(30°) ≈ 0.5
; Note: Requires linking with stdlib
LOAD R0, 3000    ; 30 degrees (scaled by 100)
CALL sin         ; Call stdlib sin function
; Result in R0 (scaled by 1000)
PRINT R0         ; Output: ~500 (0.5 × 1000)

Calculate √16 using stdlib

; Calculate √16 = 4
LOAD R0, 16000   ; 16.000 (scaled by 1000)
CALL sqrt        ; Call stdlib sqrt function
PRINT R0         ; Output: ~4000 (4.000)

Related Documentation