Skip to content

Instantly share code, notes, and snippets.

@jac18281828
Created January 1, 2026 22:09
Show Gist options
  • Select an option

  • Save jac18281828/e9d5b36fb14af5a292240c20c3e362e6 to your computer and use it in GitHub Desktop.

Select an option

Save jac18281828/e9d5b36fb14af5a292240c20c3e362e6 to your computer and use it in GitHub Desktop.
GCD Euclid using Subtraction only in MMIX
LOC #1000
Tmp IS $252
% Entry point
Main
SETI $0, 48
SETI $1, 18
PUSHJ $0, GcdEuclid
BN $1, Error
JMP Done
% ----------------------------------------------------
% Compute GCD of two non-negative integers using Euclid's algorithm
% Inputs: $0 = a, $1 = b
% Output: $0 = GCD(a, b), $1 = 0 on success, -1 on error
% ----------------------------------------------------
GcdEuclid
BN $0, GcdErrorEnd % if first number < 0, error
BN $1, GcdErrorEnd % if second number < 0,
BZ $0, AnsB % if a == 0, done
JMP IsAnsA
AnsB
SET $0, $1
JMP GcdEnd
IsAnsA BZ $1, GcdEnd % if b == 0, done
GcdLoop
CMP $10, $0, $1 % if b == a, done
BZ $10, GcdEnd
BP $10, GcdAB % if a > b, continue
SET Tmp, $0 % else if a < b, swap
SET $0, $1 % a = b
SET $1, Tmp % b = Tmp
GcdAB SUB $0, $0, $1 % a = a - b
JMP GcdLoop
GcdErrorEnd
SETI $1, -1 % return -1 for error
POP 2, 0 % return to caller
GcdEnd
SETI $1, 0
POP 2, 0 % return to caller
Done TRAP 0, Halt, 0
Error SETI $255, -1
TRAP 0, Halt, 0
TestCount IS $253
Test SETI TestCount, 0
JMP Test1
Test1 ADDUI TestCount, TestCount, 1
SETI $0, 48
SETI $1, 18
PUSHJ $0, GcdEuclid
BN $1, Error
CMPI $10, $0, 6
BZ $10, Test2
JMP Error
Test2 ADDUI TestCount, TestCount, 1
SETI $0, -1
SETI $1, 18
PUSHJ $0, GcdEuclid
SETI $2, -1
CMP $10, $1, $2
BZ $10, Test3
JMP Error
Test3 ADDUI TestCount, TestCount, 1
SETI $0, 48
SETI $1, -5
PUSHJ $0, GcdEuclid
SETI $2, -1
CMP $10, $1, $2
BZ $10, Test4
JMP Error
Test4 ADDUI TestCount, TestCount, 1
SETI $0, 0
SETI $1, 17
PUSHJ $0, GcdEuclid
BN $1, Error
CMPI $10, $0, 17
BZ $10, Test5
JMP Error
Test5 ADDUI TestCount, TestCount, 1
SETI $0, 75
SETI $1, 0
PUSHJ $0, GcdEuclid
BN $1, Error
CMPI $10, $0, 75
BZ $10, Test6
JMP Error
Test6 ADDUI TestCount, TestCount, 1
SETI $0, 6
SETI $1, 6
PUSHJ $0, GcdEuclid
BN $1, Error
CMPI $10, $0, 6
BZ $10, Done
JMP Error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment