Assembly Language Programming by Shane Zentz
# Shane Zentz
# mips program to output first 100 prime numbers
# program project part II
###################################################################
# C++ code: #
# #
# int x=1, count=0; #
# while (count < 100) #
# { #
# if (isprime(x)) #
# { #
# count++; #
# cout << x; #
# } #
# x++; #
# } #
# #
# bool isprime( int n) #
# { #
# int i=2; #
# while(i < n - 1) #
# { #
# if((n % i) == 0) #
# return false; #
# i++; #
# } #
# return true; #
# } #
#####################################################################
# Start Program
.globl main # main has to be a global label.
main:
addu $s7, $0, $ra # save the return address in a global register.
addi $s0, $0, 1 # $t0 = 1 // x = 1
add $s1, $0, $0 # $s1 = 0 // count = 0
addi $s2, $0, 100 # imm. 100 used for while loop test.
add $a0, $0, $s0 # put x into arg $a0.
blt $s1, $s2, isprime # while count < 100 call isprime(x)
bne $v0,$0, print # if isprime(x) does not equal 0 then print the integer.
#beq $s1, $t2, exit # if count == 100 then exit.
addi $s0, $s0, 1 # increment $t0 (x) regaurdless of isprime result.
#bne $s1, $s2, loop # continue loop while count does not equal 100.
# this function calls isprime but then jumps right
# back to main
.data
.globl isprime
isprime:
.text
addi $sp, $sp, -8 # make room for 2 things on stack
sw $ra, 4($sp) # save return address on stack
sw $a0, 0($sp) # save argument (n) on stack.
addi $s3, $0, 2 # i = 2
addi $s4, $a0, -1 # $t4 = n-1
div $a0, $s3 # n/i
mfhi $t5 # $t5 = n%i???
beq $t5, $0, false # if (n % i) == 0 return false.
addi $s3, $s3, 1 # increment i (i++)
blt $s3, $s4, isprime # call isprime to test again after i++.
addi $v0, $0, 1 # if all above tests fail then return 1 (true).
jr $ra
.data
.globl false
false:
.text
add $v0, $0, $0 # return false
.data
.globl print
print: .asciiz "\t" # add tab before result to print.
.text
li $v0, 4
la $a0, print
syscall
li $v0, 1 # print int (sys call 1).
add $a0, $0, $s0 # put (x) in $a0 to print..
syscall
addi $s1, $s1, 1 # increment count (count++)
jr $ra # return to caller?????????
exit:
# usual stuff at end of main.
addu $ra, $0, $s7 # restore return address.
jr $ra # return to main program
add $0, $0, $0 # nop?