CS2253/Assigments/4/fraction.asm

46 lines
1.6 KiB
NASM
Raw Permalink Normal View History

2023-05-25 18:39:26 -03:00
.ORIG x3000
LD R0, NUM
LD R1, DEN
JSR GCD
ADD R4, R1, #0
ADD R1, R2, #0
JSR DIVIDE
ST R2, NUM
ADD R0, R4, #0
JSR DIVIDE
ST R2, DEN
HALT
; you can try other values for NUM and DEN by replacing these values in the simulator
NUM .FILL #81 ; you can try other values for NUM and DEN by replacing
DEN .FILL #24
; Divide R0 by R1, putting quotient in R2 and remainder in R3
DIVIDE AND R2, R2, #0 ;clean R2
NOT R3, R1 ;store NOT of r1 in R3
ADD R3, R3, #1 ;add one to make R3 the negative of R1
ADD R5, R0, #0 ;store num in working variable
DIVLOOP ADD R2, R2, #1 ;first increment of quotient counter
ADD R5, R5, R3 ;store working number in R4, subtracting the denominator from the numerator
BRz DIVFIN
BRn DIVREM
BRp DIVLOOP
DIVREM ADD R3, R5, R1
ADD R2, R2, #-1
AND R5, R5, #0 ; clean r4
RET
DIVFIN AND R3, R3, #0 ;remainder is zero
AND R5, R5, #0 ; clean r4
RET
; Euclid's algorithm for GCD of R0 and R1, result in R2
GCD ADD R6, R7, #0 ;make call stack work (store the ret value of the original call)
GCDLOOP JSR DIVIDE
ADD R0, R1, #0 ; R0 = R1
ADD R1, R3, #0 ; R1 = R3
BRp GCDLOOP
ADD R2, R0, #0 ;result in R2
ADD R7, R6, #0 ;make call stack work (load the original ret value to return to original call location)
LD R0, NUM ;load values back into r0 (bc im bad at programming)
LD R1, DEN ;load values back into r1 (bc im bad at programming)
RET
.END