这是来自stackexchange的此链接的代码: MIPS Assembly code to find all the prime numbers below an inputted number
我正在为我的考试学习这个,但我如何修复此代码以使其打印出来自2-N的素数
作为链接中的帖子,我能够从答案中完成第二步,但目前我在代码中难以实现第1步
以下是代码中出现的两个问题: 有两个问题:
当你增加i时,你忘记将j设置为2. L3应移动1行 起来。 (执行此困难)
小于或等于,因此您的代码实际上是在检查j< = 我,而不是j<一世。这导致您的代码在i = j时检查i%j,这总是如此 余数为0,将注册为非素数。改变'变化'到了' blt' 应该解决这个问题同样适用于i<检查。
以下是代码:
# 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 ","
提前致谢:]