【汇编程序】实现输出1000以内所有素数(Prime number)
程序需求:编程写一个完整的程序,求出1000以内的所有素数,并将它们存入Prime数组中,素数的个数存入变量Pcounter中。
编程思路:esi相当与C中的i,edi相当与C中的j,ecx相当于C中的Pcounter。
开发环境
Win10 + VS2017
C语言代码实现如下:
#include <stdio.h>
int Prime[1000];
int main()
{
int Pcounter = 0;
for (int i = 6; i < 1000; i++)
{
for (int j = 2; j < i/2; j++)
{
if (i%j == 0)
break;
if (j == i / 2 - 1)
Prime[Pcounter++] = i;
}
}
printf("2\t3\t5\t");
for (int i = 0; i < Pcounter; i++)
printf("%d\t", Prime[i]);
return 0;
}
汇编语言代码实现如下:
INCLUDELIB kernel32.lib
INCLUDELIB ucrt.lib
INCLUDELIB legacy_stdio_definitions.lib
.386
.model flat,stdcall
ExitProcess PROTO,
dwExitCode:DWORD
printf PROTO C : dword,:vararg
scanf PROTO C : dword,:vararg
.data
format byte '%d',9,0;
msg byte 32h,9,33h,9,35h,9,0
Prime dword 0 dup(1000)
.code
main Proc
xor ecx,ecx;ecx==Pcounter
mov esi,6;esi==i
jmp testing
body:
mov edi,2;cdi==j
jmp testing2
body2:
mov eax,esi
mov ebx,edi
cdq
div ebx
cmp edx,0
jne next
jmp over
next:
mov eax,esi
mov ebx,2
cdq
div ebx
dec eax
cmp edi,eax
jne over2
mov dword ptr Prime[ecx*4],esi
inc ecx
over2:
inc edi
testing2:
mov eax,esi
mov ebx,2
cdq
div ebx
cmp edi,eax
jl body2
over:
inc esi
testing:
cmp esi,1000
jl body
pushad
invoke printf,offset msg
popad
xor esi,esi
again:
pushad
invoke printf,offset format,dword ptr Prime[esi*4]
popad
inc esi
loop again
push 0h
call ExitProcess
main endp
end main