汇编语言判断素数基于masm
时间: 2023-09-10 11:14:20 浏览: 261
以下是基于 MASM 的汇编语言程序,用于判断一个输入的整数是否为素数:
```
.386
.model flat,stdcall
.stack 4096
ExitProcess PROTO, dwExitCode:DWORD
.data
msg1 db "Enter a number: ", 0
msg2 db " is a prime number.", 0
msg3 db " is NOT a prime number.", 0
num dd ?
.code
main PROC
; Display message to enter a number
mov eax, offset msg1
call WriteString
; Read integer input from user
call ReadInt
mov num, eax
; Check if input number is prime
mov ecx, 2
mov ebx, 0
L1:
mov edx, 0
div ecx
cmp edx, 0
je L2
inc ecx
cmp ecx, num
jne L1
mov ebx, 1
L2:
; Display result
mov eax, num
call WriteInt
cmp ebx, 0
je not_prime
mov eax, offset msg2
call WriteString
jmp exit_prog
not_prime:
mov eax, offset msg3
call WriteString
exit_prog:
invoke ExitProcess, 0
main ENDP
; Function to read integer input from user
ReadInt PROC
push ebp
mov ebp, esp
sub esp, 8
mov eax, 3
mov edx, offset num
mov ecx, 10
call ReadConsole
mov eax, num
add esp, 8
pop ebp
ret
ReadInt ENDP
; Function to display integer value
WriteInt PROC
push ebp
mov ebp, esp
sub esp, 8
mov eax, 1
mov edx, offset num
mov ecx, 10
call WriteConsole
add esp, 8
pop ebp
ret
WriteInt ENDP
; Function to display string
WriteString PROC
push ebp
mov ebp, esp
sub esp, 8
mov eax, 0
mov edx, [ebp + 8]
call WriteConsole
add esp, 8
pop ebp
ret
WriteString ENDP
END main
```
该程序的实现思路是,先读取用户输入的整数,然后从2开始逐个除以整数,并判断余数是否为0。如果余数为0,则说明该整数不是素数,否则继续除以下一个整数,直到除到该整数本身为止。如果除到最后都没有余数为0,则说明该整数是素数。
注意,该程序只能判断输入的整数是否为素数,没有做输入合法性检查。如果输入的不是整数,程序会出现异常。
阅读全文