PrimeCheck 8086 装配错误

PrimeCheck 8086 Assembly Bug

我写了一个 8086 汇编程序,它做了以下事情:

  1. 获取用户的输入
  2. 将其转换为整数
  3. 检查是否为素数

问题出在第 3 步,它有一个错误。 它说 9 是质数,当输入为 2 时处于无限循环中。 我检查了,输入没有问题。 不知道是什么问题

代码:

    MOV AL,NUM
    MOV BL,02H      ; The Dividing starts from 2, Hence BH is compare to 02H
    MOV DX,0000H    ; To avoid Divide overflow error
    MOV AH,00H      ; To avoid Divide overflow error

循环检查素数

L1:
    DIV BL
    CMP AH,00H      ; Remainder is compared with 00H (AH)
    JNE NEXT
    INC BH          ; BH is incremented if the Number is divisible by current value of BL
NEXT:
    CMP BH,02H      ; If BH > 02H, There is no need to proceed, It is not a Prime
    JE FALSE        ; The no is not a Prime No
    INC BL          ; Increment BL
    MOV AX,0000H    ; To avoid Divide overflow error
    MOV DX,0000H    ; To avoid Divide overflow error
    MOV AL,NUM      ; Move the Default no to AL
    CMP BL,NUM      ; Run the loop until BL matches Number. I.e, Run loop x no of times, where x is the Number given
    JNE L1          ; Jump to check again with incremented value of BL

打印结果:

    ;To display The given no is a Prime No
TRUE:
    LEA DX,MSG
    MOV AH,09H      ; Used to print a string
    INT 21H
    JMP EXIT

    ;To display The given no is not a Prime No
FALSE:    
    LEA DX,NMSG
    MOV AH,09H      ; Used to print a string
    INT 21H

我认为它只发生在一位数字上。

CMP BH,02H
JE FALSE
;
CMP BL,NUM
JNE L1   

这是你的问题。

如果您不允许将数字除以自己,那么您的 false 标准应该变成 CMP BH, 1.
如果您确实允许将数字除以自身(但为什么要这样做?)检查 BH=2 是否正确。


从除以 2 到 N-1 得到零余数后,该数字就不是素数。
例如对于数字 9,除以 2、3、4、5、6、7、8 零余数已经发生在 3 处,因此 'not prime'

 MOV  BL, 2
L1:
 XOR  AX, AX
 MOV  AL, NUM
 DIV  BL
 TEST AH, AH
 JZ   FALSE
 INC  BL
 CMP  BL, NUM
 JB   L1    

is in an infinite loop when input is 2.

你必须挑出那种情况。对于数字 2,您不能从 2 迭代到 N-1。
您可以安全处理的最小数字是 3(2 到 2)。

您的代码在此崩溃的原因是因为您使用了 JNE L1。在我的代码片段中查看我是如何使用 JB L1 的?