天天看点

【8086汇编】输入一个整数,判断其是否为素数(质数)(输入范围:2~32767,带提示信息)

【8086汇编】输入一个整数,判断其是否为素数(质数)(输入范围:2~32767,带提示信息)

图 1 程序运行示意

【8086汇编】输入一个整数,判断其是否为素数(质数)(输入范围:2~32767,带提示信息)

图 2 程序运行示意(边界数据和5位整数)

stack   segment stack
        db 512 dup(?)
stack   ends
    
data    segment
		string0 db "Enter a decimal number(2~32767):", 0ah, 0dh, '$'
        string1 db "Press any key to continue!", 0ah, 0dh, '$'
		string2 db " is prime.", 0ah, 0dh, '$'
		string3 db " is not prime.", 0ah, 0dh, '$'
data    ends
		
code 	segment
        assume ds: data, cs: code, ss: stack
main:
		mov ax, stack
        mov ss, ax
		mov ax, data
        mov ds, ax
		
		lea dx, string0
		mov ah, 09h
		int 21h
		
		call	far ptr readsiw
		push ax
		
		call	far ptr is_prime
		push ax
		cmp ax, 0
		je isNotPrime
		jmp isPrime
isNotPrime:
		pop ax
		pop ax
		call	far ptr dispsiw
		lea dx, string3
		mov ah, 09h
		int 21h
		jmp to_finish

isPrime:
		pop ax
		pop ax
		call	far ptr dispsiw
		lea dx, string2
		mov ah, 09h
		int 21h
		jmp to_finish

is_prime	proc	far
		push	bp
		mov	bp,sp
		push	si
		push	di
		mov	di,word ptr [bp+6]
		
		mov	si,2					; for(i = 2; i * i <= n; i++)
		jmp	short multi_equal
sqrt_mod:	
		mov	ax,di
		cwd	
		idiv	si
		or	dx,dx
		jne	short loop_multip		; if(n % i == 0)	
		xor	ax,ax					; return 0
Its_prime:
		jmp	short judge_finish
loop_multip:
		inc	si
multi_equal:
		mov	ax,si
		imul	si
		cmp	ax,di
		jle	short sqrt_mod
		
		mov	ax,1					;		return 1
		jmp	short Its_prime
judge_finish:	
		pop	di
		pop	si
		pop	bp
		ret	
is_prime	endp

readsiw proc	far
		push bx
		push cx
		push dx
		xor bx, bx   
		xor cx, cx   
		mov ah, 1
		int 21h
		cmp al, '+'
		jz rsiw1
		cmp al, '-'
		jnz rsiw2
		mov cx, -1
rsiw1: 
		mov ah,  1
		int 21h
rsiw2:    
		cmp al, '0'
		jb rsiw3
		cmp al, '9'
		ja rsiw3
		sub al, 30h
		xor ah, ah
		shl bx, 1
		mov dx, bx
		shl bx, 1
		shl bx, 1
		add bx, dx
		add bx, ax
		jmp rsiw1
rsiw3:
		cmp cx, 0
		jz rsiw4
		neg bx
rsiw4:
		mov ax, bx
		pop dx
		pop cx
		pop bx
		ret
readsiw endp

dispsiw proc	far
		push ax
		push bx
		push dx
		test ax, ax 
		jnz dsiw1
		mov dl, '0' 
		mov ah, 2
		int 21h
		jmp dsiw5
dsiw1:
		jns dsiw2  
		mov bx, ax
		mov dl, '-'
		mov ah, 2
		int 21h
		mov ax, bx
		neg ax 
dsiw2:  
		mov bx, 10
		push bx 
dsiw3:
		cmp ax, 0
		jz dsiw4
		xor dx, dx 
		div bx  
		add dl, 30h  
		push dx     
		jmp dsiw3
dsiw4:
		pop dx
		cmp dl, 10
		je dsiw5
		mov ah, 2
		int 21h
		jmp dsiw4
dsiw5:
		pop dx
		pop bx
		pop ax
		ret
dispsiw endp

lineFeed proc	far
		push ax
		push dx
		mov dl, 0dh
		mov ah, 2
		int 21h
		mov dl, 0ah
		mov ah, 2
		int 21h
		pop dx
		pop ax
		ret
lineFeed endp
	
to_finish:
		lea dx, string1
		mov ah, 09h
		int 21h
		
		mov ah, 07h
		int 21h
		
		
		mov ah, 4ch
		int 21h
code	ends
		end main
           

继续阅读