Skip to content

Instantly share code, notes, and snippets.

@MrYakobo
Last active May 22, 2017 09:23
Show Gist options
  • Save MrYakobo/a0cc8d57ae6b9d8347417a2699b46158 to your computer and use it in GitHub Desktop.
Save MrYakobo/a0cc8d57ae6b9d8347417a2699b46158 to your computer and use it in GitHub Desktop.
factorial in ARM assembly
;R0 parameter
factorial
PUSH {R1, R2, LR}
CMP R0, #1
BEQ ret ; return 1
MOV R1, R0 ; kopiera R0 till R1
SUB R0, R0, #1 ; dec R0
BL factorial ; anropa factorial
MUL R2, R1, R0 ; int result = fact(n-1)*n
MOV R0, R2 ; R0 = result
POP {R1, R2, LR} ; return
ret
MOV R0, #1 ;return 1
POP {R1, R2, LR} ; return
fact ; Assume R0 contains the input value,
; and R0 is also containing the return value
PUSH {R1,LR}
MOV R1,R0 ; R1 = n
CMP R0,#1 ; if n>1 recursively call
BGT fact_next
MOV R0,#1 ; if n<=1 the return 1
B fact_return
fact_next
SUB R0,R0,#1 ;
BL fact ; call fact(n-1)
MUL R0,R0,R1 ; return fact(n-1) * n
fact_return
POP {R1,PC}
main
MOV R1, #5
MOV R2, #1
BL REK
STOP B STOP
REK
CMP R1, #0
IT EQ
BXEQ LR
MUL R2, R2, R1
SUB R1, R1, #1
BL REK
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment