# divisBy. This method will take a large and small number (first and second post-stack bytes), and # return in $1 1 if large is divisible by small, and 0 if not # Register Usage: # $4 - the larger number, this gets $3 subtracted from it until it is less than or equal to zero # $3 - the smaller number, this keeps subtracting from $4 until it is less than or equal to zero .globl divisby divisby: addi $30,$30,-8 # gets us 2 bytes of stack space sw $4,0($30) # stores $4 sw $3,4($30) # stores $3 lw $4,8($30) # loads the larger number lw $3,12($30) # loads the smaller number divLoop: sub $4,$4,$3 # subtracts smaller from temporary beq $4,$0,isDiv # if we hit exactly zero, then large is divisible bgtz $4,divLoop # if we haven't hit zero yet, subtract again # assertion: $4 is less than 0 now, large is not divisible notDiv: addi $1,$0,0 # if we are less than zero, then larger is not divisible by smaller j divCleanup # jump to the routine cleanup function isDiv: addi $1,$0,1 # if we are here, then larger IS divisible j divCleanup # jump to cleanup divCleanup: lw $4,0($30) # loads the old $4 lw $3,4($30) # loads the old $3 addi $30,$30,8 # returns those 2 bytes of stack space jr $31 # returns to caller # isPrime. This method takes a number, and uses divisBy to check if it is divisible by every number smaller # than it. It returns $1=1 if it is a prime, $1=0 if it isn't # Register Usage: # $4 - the number we are checking for primage (call it n) # $3 - counts from 2 to n, checks for divisibility each time # $31 - from jal-ing to divisby a bunch of times isPrime: addi $30,$30,-12 # we need to store 2 bytes worth on the stack sw $4,0($30) # store $4 on the stack sw $3,4($30) # store $3 on the stack sw $31,8($30) # store $31 on the stack, because we jal in this method lw $4,12($30) # loads our parameter from the top of the stack as it was addi $3,$0,2 # loads our starting check primeLoop: addi $30,$30,-8 # clears some stack space for parameter-passing sw $4,0($30) # puts the big number at the top sw $3,4($30) # puts the small number 2nd from the top jal divisby # calls divisBy to check for divisibility addi $30,$30,8 # reclaims stack space bne $1,$0,notPrime # if $1 != 0, then this is divisible by our test, and it isn't prime addi $3,$3,1 # adds 1 to our test number beq $3,$4,goodPrime # if #3 managed to get all the way to $4 without triggering notPrime, this is a prime notPrime: addi $1,$0,0 # set $1 = 0 because this is not a prime j primeCleaup # go to the cleanup stuff goodPrime: addi $1,$0,1 # set $1 = 1 because this is a prime j primeCleaup # go to cleanup stuff primeCleaup: lw $4,0($30) # restores $4 lw $3,4($30) # restores $3 lw $31,8($30) # restores $31 jr $31