MIPS汇编代码以查找输入数字下方的所有素数 [英] MIPS Assembly code to find all the prime numbers below an inputted number
问题描述
下面,我发布了我的MIPS代码.我基于它的Java代码是...
Below I have posted my MIPS code. The java code I am basing it off on is...
Java代码...
Java Code...
for (int i=2;i<n;i++){
p = 0;
for (int j=2;j<i;j++){
if (i % j == 0)
p = 1;
}
if (p = 0) System.out.println(i);
}
我添加了"beq $ t3,1,L4"行,以在将p设置为1时跳到L4以节省时间.但是,当我添加这一行代码时,该程序什么也不输出.在添加此行之前,它将打印2〜n中的所有整数.
I have added the line "beq $t3, 1, L4" to skip to L4 when p is set to 1 to save time. But when I added this line of code, the program outputs nothing. Before I added this line, it would print all the integers from 2~n.
MIPS代码...
MIPS Code...
# The number is read through the keyboard
.text
.globl main
main:
# Display message to user for a number
li $v0, 4
la $a0, prompt1
syscall
# read keyboard into $v0 (number x is upper bound number to find primes)
li $v0, 5
syscall
# move the number from $v0 to $t0
move $t0, $v0 # $t0 = n
# store 2 in $t1 and $t2
li $t1, 2 # i
li $t2, 2 # j
L3: # for (int i=2; i<n; i++)
# store 0 in $t3
li $t3, 0 # p = 0;
L2: # for (int j=2; j<i; j++)
# do div of two numbers
div $t2, $t1
# store the remainder in $t4
mfhi $t4
# branch if remainder is not 0 to L1
bne $t4, 0, L1 # if (i % j == 0)
# set $t3 as 1
li $t3, 1 # p = 1
# if p=1 break to next i
beq $t3, 1, L4
L1: # if (i % j == 0)
# add 1 to t2
addi $t2, $t2, 1 # j++
# repeat code while j < i
ble $t2, $t1, L2
# print integer function call 1
# put the answer into $a0
li $v0, 1
move $a0, $t1
syscall # System.out.println(i)
#print comma
li $v0, 4
la $a0, comma
syscall
L4:
# add 1 to t1
addi $t1, $t1, 1 # i++
# repeat code while i < n
ble $t1, $t0, L3 # for (int i=2; i<n; i++)
.data
prompt1:
.asciiz "Enter a number "
comma:
.asciiz ","
我认为发生此错误是因为我的汇编逻辑未考虑j<我的for循环的一部分.我在正确的轨道上吗?
I think the error occurs because my assembly logic is not accounting for the j < i portion of the for loop. Am I on the right track?
推荐答案
有两个问题:
-
当您增加i时,您会忘记将j设置为2.L3应该向上移动1行.
When you increment i you forget to set j back to 2. L3 should be moved 1 line up.
ble小于或等于,因此您的代码实际上是在检查 j< = i ,而不是 j<我.这将导致您的代码在i = j时检查 i%j ,该值始终为0,并且将注册为非素数.将'ble'更改为'blt'应该可以解决此问题. i< n检查.
ble in MIPS is less than or equal to, so your code is actually checking j <= i, not j < i. This causes your code to check i % j when i = j, which always has a remainder 0 and will register as not prime. Changing 'ble' to 'blt' should fix this. Same goes for the i < n check.
还有一些其他的建设性批评:您设置p = 1,然后立即进行检查以查看p = 1.
Also some additional constructive criticism: You set p=1 then immediately do a check to see if p = 1.
li $t3, 1 # p = 1
beq $t3, 1, L4 # if p=1 break to next i
您可以删除具有p的冗余,完全删除p并用对L4的无条件分支替换这两行
You can take out the redundancy of having p, removing p altogether and replacing these two lines with an unconditional branch right to L4
b L4
这篇关于MIPS汇编代码以查找输入数字下方的所有素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!