[英]Printing Prime Numbers in Assembly
我正在嘗試從匯編中的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(都是質數)整除嗎?
您沒有在isPrime
的循環內正確重置EDX
。 也就是說,在div k
之前,您需要放置mov edx,0
或xor edx,edx
。
另外,我不確定在函數(?)開頭div num
中num
來源。 評論說您要除以2,那么您的意思是div k
嗎?
而且程序中有一些不必要的代碼。 像這樣檢查:
cmp ecx, 0 ; while prime
jne E ; if prime isnt true
如果您看一下其余的代碼,則應該清楚的是, ECX
在那一點永遠不會有除零以外的任何其他值。
當您在k = k + 1處增加k時,會忘記清除edx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.