汇编语言输入一个数判断素数masm
时间: 2024-05-05 21:22:16 浏览: 12
下面是一个汇编程序,可以输入一个数并判断是否为素数:
```
.model small
.stack 100h
.data
msg1 db 10, 13, "Please enter a number: $"
msg2 db 10, 13, "The number is prime. $"
msg3 db 10, 13, "The number is not prime. $"
.code
main proc
mov ax, @data
mov ds, ax
; print message to enter a number
lea dx, msg1
mov ah, 9
int 21h
; read in the number
mov ah, 1
int 21h
sub al, '0' ; convert ASCII to number
mov bl, al ; save the number in BL
; check if the number is prime
mov cl, 2 ; start by dividing by 2
mov ah, 0 ; clear AH
div cl ; divide AL by CL
cmp ah, 0 ; check if remainder is zero
je not_prime ; if remainder is zero, the number is not prime
; continue checking for prime
mov cl, 3 ; divide by 3
check_prime:
cmp cl, bl ; if we reach the number itself, it is prime
jg is_prime
mov ah, 0 ; clear AH
div cl ; divide AL by CL
cmp ah, 0 ; check if remainder is zero
je not_prime ; if remainder is zero, the number is not prime
add cl, 2 ; increment CL by 2 (since even numbers are not prime)
jmp check_prime
is_prime:
; print message that the number is prime
lea dx, msg2
mov ah, 9
int 21h
jmp exit
not_prime:
; print message that the number is not prime
lea dx, msg3
mov ah, 9
int 21h
exit:
mov ah, 4ch
int 21h
main endp
end main
```
该程序使用 21h 中断来进行输入和输出。它首先打印出一个消息来提示用户输入一个数字。然后,它使用 21h 中断来读取用户输入的数字,并将其保存在 BL 寄存器中。接下来,它从 2 开始除以该数字,并检查余数是否为零。如果余数为零,则该数字不是素数。否则,它继续除以 3、5、7 等奇数,直到达到该数字本身。如果该数字不是素数,它打印出一个消息来告诉用户。如果该数字是素数,它打印出另一个消息来告诉用户。最后,程序使用 21h 中断来退出。