0

我正在重写我对 MIPS 程序集中 Project Euler 问题的答案,但我无法让这个答案输出正确的答案。我已经检查了过去一个小时的代码,但我无法弄清楚我的方法有什么问题(因为当答案比这高出 200,00+ 时,我得到了 33165),所以我想出了问题一定是我对语法的摇摆不定。我在这里做了什么愚蠢的事情,比如使用保留寄存器?

## p1.asm
## 
## Andrew Levenson, 2010
## Project Euler, Problem 1
## In MIPS Assembly for SPIM

## Calculate the sum, s, 
## of all natural numbers, n,
## Such that n < 1000.
        .text
        .globl  main

main:
        ori     $8, $0, 0x0     # Init sum s in $8 to 0
        ori     $9, $0, 0x0     # Init variable number n in $9 to 0
        ori     $10, $0, 0x3    
        ori     $11, $0, 0x5
        la      $14, lim         


loop:
retry:
        addiu   $9, $9, 0x1     # Increment n by 1

    # Is n less than 1000?
        sltiu   $15, $9, 1000   # if n >= 1000 then jump to print
        beq     $15, $0, print  # if $15 == 0 

        sll     $0, $0, $0      # no op


    # Is n a multiple of three or five?
        div     $9, $10         # n / 3
        mflo    $12             # $12 = floor( n / 3 ) 
        mfhi    $13             # $13 = n mod 3 

        bne     $13, $0, retry  # if n mod 3 != 0 then retry
        sll     $0, $0, $0      # no op
        beq     $13, $0, sum    # else, print
        sll     $0, $0, $0      # no op

        div     $9, $11         # n / 5
        mflo    $12             # $12 = floor( n / 5 ) 
        mfhi    $13             # $13 = n mod 5 

        bne     $13, $0, retry  # if n mod 5 != 0 then retry
        sll     $0, $0, $0      # no op

    # If we've made it this far, n is good!
sum:
        addu    $8, $8, $9      # s = s + n

        j       loop            # jump to loop
        sll     $0, $0, $0      # no op


print:
        li      $v0, 1          # system call #1 - print int
        move    $a0, $8
        syscall                 # execute

exit:   
        li      $v0, 0xA        # system call #10 - exit
        syscall 



## End of Program

## Variable declarations    
                .data
lim:            .word   1000    # loop bound

编辑:代码自发布以来进行了调整。提出了修复建议,但它仍然会产生大约 100,000 的答案。:(

4

1 回答 1

1

通过3在每个循环中增加 $9,您将丢失许多倍数5,从5...

更新:通过分支 when$9不能被 3 整除,然后被 5 整除,您只保留 35 的倍数。

更新:您必须删除以下行:

bne     $13, $0, retry  # if n mod 3 != 0 then retry
于 2010-07-22T06:42:41.020 回答