Skip to content

Instantly share code, notes, and snippets.

@tbnbooij
Created February 24, 2018 11:38
Show Gist options
  • Save tbnbooij/0aae329c748d6ffaa8e5a7497c164469 to your computer and use it in GitHub Desktop.
Save tbnbooij/0aae329c748d6ffaa8e5a7497c164469 to your computer and use it in GitHub Desktop.
A small script in MIPS assembly to calculate the greatest common divisor of two integer values.
# Greatest Common Divisor
# Written in MIPS Assembly by T.B.N. Booij
# February 23rd, 2018
# Definitions
# $a0 = a, $a1 = b
# Under the assumption that a >= b
.data
tab: .asciiz "\t"
newline: .asciiz "\n"
finalmsg: .asciiz "The greatest common divisor is "
.text
main:
li $a0, 300 # Input value a
li $a1, 18 # Input value b
jal gcd # Jump-and-link to gcd
move $t0, $v0 # Move return value to temporary register
li $v0, 4 # Load code for print_string
la $a0, finalmsg # Load string to a0
syscall
li $v0, 1 # Load code for print_int
move $a0, $t0 # Move return value to print_int argument
syscall # Print return value to screen
li $v0, 10 # Exit program
syscall
gcd:
# Push the return address on the stack
addi $sp, $sp, -4 # Push one item on the stack
sw $ra, 0($sp) # Save return address
# Printing arguments to screen
addi $sp, $sp, -4 # Push one item on the stack
sw $a0, 0($sp) # Save a0 on the stack
li $v0, 1 # Load code for print_int
syscall # Print a to the screen
li $v0, 4 # Load code for print_string
la $a0, tab # Load address for tab string
syscall # Print tab to screen
li $v0, 1 # Load code for print_int
move $a0, $a1 # Load b to a0
syscall # Print b to the screen
li $v0, 4 # Load code for print_string
la $a0, newline # Load address for newline string
syscall # Print newline to screen
lw $a0, 0($sp) # Restore original value of a0
addi $sp, $sp, 4 # Pop one item from the stack
# Function body
move $t0, $a0 # Save a as temporary value
bne $a1, $zero, mod # If b != 0, jump to mod
# Function return
addi $sp, $sp, 4 # Pop item from the stack (return address is still in $ra)
move $v0, $a0 # Load return value (a)
jr $ra # Finish the function
mod:
blt $t0, $a1, endmod # Jump to endmod if temp_a < b
sub $t0, $t0, $a1 # temp_a = temp_a - b
j mod
endmod:
move $a0, $a1 # Swap the input arguments
move $a1, $t0
jal gcd # And call gcd again
endgcd:
lw $ra, 0($sp) # Load return address
addi $sp, $sp, 4 # Pop three items from the stack
jr $ra # Jump to return address
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment