【问题标题】:Printing Prime Numbers in Assembly在装配中打印素数
【发布时间】:2014-09-19 03:24:03
【问题描述】:

我正在尝试在汇编中打印 1-100 的素数,但我的代码不仅打印出额外的数字,而且还排除了一些素数。

这是我的主要程序:

mov min, 1

loopStart:
  inc min                    ; min++
  mov eax, min
  cmp eax, max               ; compare 2 and 100
  je  next                   ; jump unless 2 < 100

  call isPrime               ; check if prime
  cmp ecx, 0
  jne loopStart 
push eax
  call printPrime            ; print the prime numbers
pop eax
  jmp loopStart

  next:                      ; once max is 100

  push 0                          
  call ExitProcess

我的 isPrime 是:

mov prime, 0                 ; set as true
mov ecx, prime                  
mov k, 2                     ; reset k 

mov edx, 0                   ; clear edx
div num                      ; n/2
mov edx, 0                   ; clear edx again

start:
cmp ecx, 0                   ; while prime
jne E                        ; if prime isnt true

cmp eax, k                   ; k<=n/2
jl E

mov eax, min
div k
cmp edx, 0                   ; check for remainder
jne kAdd

mov prime, 1                 ; set as false
jmp E

kAdd:
inc k
jmp start

E:
mov ecx, prime
mov eax, min

ret
isPrime endp

打印出来:2 3 5 7 13 15 19 21 25 31 33 37 39 43 49 51 55 57 61 63 67 73 75 79 81 85 91 93 97 99

大多数额外的数字都可以被 3、5 和 7(它们都是质数)整除的事实是否与某些事情有关?

【问题讨论】:

  • 到目前为止你做了哪些调试?您是否尝试过在调试器中单步执行它,以查看当它报告不正确的素数时发生了什么?

标签: assembly printing x86 primes


【解决方案1】:

您没有在isPrime 的循环内正确重置EDX。也就是说,在div k 之前需要放一个mov edx,0xor edx,edx

另外,我不确定函数开头的div num 中的num 来自哪里(?)。评论说你要除以 2,所以你的意思是 div k

您的程序中有一些不必要的代码。像这样的检查:

cmp ecx, 0                   ; while prime
jne E                        ; if prime isnt true

如果您查看代码的其余部分,您应该清楚ECX 在那时不会有任何其他值。

【讨论】:

    【解决方案2】:

    在 k = k + 1 处增加 k 时忘记清除 edx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 2018-11-27
      • 1970-01-01
      • 2011-02-18
      • 2016-08-11
      • 1970-01-01
      相关资源
      最近更新 更多