Search code examples
mips32mars-simulator

MIPS Assembly finding if prime or not


I wrote this code to check if something is a prime number or not.

    .data
is_prime:   .asciiz "--Prime--"
not_prime:  .asciiz "--No prime--"
element:    .word 2

    .text
main:
    #importeer prime messages
    la $t3, is_prime
    la $t4, not_prime
    lw $t1, element
    # input variabele n
    li $v0, 5
    syscall
    move $t0, $v0

if_loop:
    beq $t0, 1, prime_true
    bgt $t0, 1, prime_check

prime_check:
    beq $t0, $t1, prime_true
    div $t1, $t0
    mfhi $t6
    beq $t6, 0, prime_false
    addi $t0, $t0, 1

prime_true:
    li $v0, 4
    move $a0, $t3
    syscall
    j exit
prime_false:
    li $v0, 4
    move $a0, $t4
    syscall
    j exit
exit:

However, every time I run it with any input like 3, 4, 5 or 6 it gives --Prime-- when for 4 and 6 it shouldn't.


Solution

  • My MIPS is quite rusty, but as I understand your code, the value you want to check is in $t0 and the incrementing divisor is in $t1. So your code has the following issues

    • div $t1, $t0 calculates $t1 / $t0. You want to calculate $t0 / $t1, so switch the parameters (as you already noticed yourself)

    • you are lacking a j if_loop somewhere -- probably best after addi -- for your loop to continue after you checked the remainder of the division. So for any odd number your code will just continue running straight ahead and print out "--Prime--"

    • addi $t0, $t0, 1 is incrementing the value you want to check, instead of the divisor. You have to addi $t1, $t1, 1 instead