【发布时间】:2019-06-21 17:03:16
【问题描述】:
我编写了一个 8086 汇编程序,它执行以下操作:
- 从用户那里获取输入
- 将其转换为整数
- 检查是否为素数
问题出在第 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
我认为这只发生在一位数字上。
【问题讨论】:
-
你似乎没有初始化
BH。 -
一开始就设置为零。没问题
-
那么请发布您的实际代码。
-
所有数字
n <= 3都是素数,这是一种特殊情况,因此您可以在循环中跳过偶数除数。另请参阅Checking if a number is prime in NASM Win64 Assembly/ 以获得更有效的质数检查循环,该循环检查除数的商以停止在sqrt(n)左右,而不是无用地一直上升到n-1。将算法移植到 8 位整数的 x86-16 应该很简单。