简体   繁体   English

在汇编中打印素数

[英]Printing Prime Numbers in Assembly

I'm trying to print prime numbers from 1-100 in assembly, but not only is my code printing out extra numbers, but also excluding some prime numbers. 我正在尝试从汇编中的1-100打印素数,但是我的代码不仅打印出多余的数,而且还排除了一些素数。

Here is my main procedure: 这是我的主要步骤:

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

And my isPrime is: 我的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

It prints out: 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 它打印出: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

Is the fact that most of the extra numbers are divisible by 3, 5, and 7 (which are all prime numbers) have to do with something? 事实是,大多数额外数字都可以被3、5和7(都是质数)整除吗?

You're not properly resetting EDX inside the loop in isPrime . 您没有在isPrime的循环内正确重置EDX That is, before div k you need to put a mov edx,0 or xor edx,edx . 也就是说,在div k之前,您需要放置mov edx,0xor edx,edx

Also, I'm not sure where num comes from in div num at the beginning of the function(?). 另外,我不确定在函数(?)开头div numnum来源。 The comment says that you're dividing by 2, so did you mean div k ? 评论说您要除以2,那么您的意思是div k吗?

And there's some unnecessary code in your program. 而且程序中有一些不必要的代码。 Like this check: 像这样检查:

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

If you look at the rest of the code it should become clear that ECX never will have any other value than zero at that point. 如果您看一下其余的代码,则应该清楚的是, ECX在那一点永远不会有除零以外的任何其他值。

当您在k = k + 1处增加k时,会忘记清除edx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM