首页 > 解决方案 > 不使用分支指令的 n 个自然数(1 到 n)的 MIPS 代码总和

问题描述

.data
input: .asciiz "Enter limit for the sum of natural number = "
show: .asciiz " \n sum of natural numbers are =   "

.text
main:
#get the integer input from user
    li $v0, 4
    la $a0, input
    syscall
    li $v0, 5
    syscall
    move $s5, $v0
    li $v0, 1
    move $a0, $s5
    syscall
    
    addi $t5, $t5, 0
iteration:
    blt $t5, $s5, increment 
    j end
increment:  
    add $s2, $s2, $t5
    addi $t5, $t5, 1
j iteration
end:    
    li $v0, 4
    la $a0, show
    syscall  
    
    li $v0, 1
    move $a0, $s2
    syscall

好的,所以我知道如何通过用户输入使用分支指令来获取 n 个自然数的总和,但我的问题是:“如何在不使用分支指令(bge、bltv bne 等)的情况下执行相同的程序”

标签: assemblyconditional-statementsmipsmips32

解决方案


1..n 之和等于 (n*(n+1))/2

在伪代码中:

temp := (input + 1)
temp := (temp * input)
result := (temp >> 1)

推荐阅读