C代码:
#include <stdio.h>
int main()
{
unsigned guess; /* current guess for prime */
unsigned factor; /* possible factor of guess */
unsigned limit; /* find primes up to this value */
printf("Find primes up to: ");
scanf("%u", &limit);
printf("2\n"); /* treat first two primes as special case */
printf("3\n");
guess = 5; /* initial guess */
while ( guess <= limit ) {
/* look for a factor of guess */
factor = 3;
while ( factor*factor < guess && guess % factor != 0 )
factor += 2;
if ( guess % factor != 0 )
printf("%d\n", guess);
guess += 2; /* only look at odd numbers */
}
return 0;
}
汇编代码(NASM):
%include "asm_io.inc"
segment .data
Message db "Find primes up to: ", 0
segment .bss
Limit resd 1 ; find primes up to this limit
Guess resd 1 ; the current guess for prime
segment .text
global _asm_main
_asm_main:
enter 0,0 ; setup routine
pusha
mov eax, Message
call print_string
call read_int ; scanf("%u", & limit );
mov [Limit], eax
mov eax, 2 ; printf("2\n");
call print_int
call print_nl
mov eax, 3 ; printf("3\n");
call print_int
call print_nl
mov dword [Guess], 5 ; Guess = 5;
while_limit: ; while ( Guess <= Limit )
mov eax,[Guess]
cmp eax, [Limit]
jnbe end_while_limit ; use jnbe since numbers are unsigned
mov ebx, 3 ; ebx is factor = 3;
while_factor:
mov eax,ebx
mul eax ; edx:eax = eax*eax
**jo end_while_factor ; if answer won't fit in eax alone**
cmp eax, [Guess]
jnb end_while_factor ; if !(factor*factor < guess)
mov eax,[Guess]
mov edx,0
div ebx ; edx = edx:eax % ebx
cmp edx, 0
je end_while_factor ; if !(guess % factor != 0)
add ebx,2 ; factor += 2;
jmp while_factor
end_while_factor:
**je end_if ; if !(guess % factor != 0)**
mov eax,[Guess] ; printf("%u\n")
call print_int
call print_nl
end_if:
mov eax,[Guess]
add eax, 2
mov [Guess], eax ; guess += 2
jmp while_limit
end_while_limit:
popa
mov eax, 0 ; return back to C
leave
ret
如您所见,我用**标记了两条指令。
首先,MUL 指令将 EAX*EAX 相乘并将值存储在 EDX:EAX 中,如果它太大而无法容纳 EAX,对吧?然后程序检查溢出。那么当值太大而无法适应 EAX 时,系统会检测到溢出并设置 OF=1?为什么?如果需要,该值是否不会同时存储在 EAX 和 EDX 中?
其次,JE指令。评论解释说:如果!(猜测%因子!= 0)。
当程序从那里跳转时没关系:
cmp edx,0
je end_while_factor
但是如果跳转是因为溢出检查,或者如果 !(factor*factor < 0)?会好吗?正在比较哪些值?它只是检查ZF?但是它之前不是因为另一个原因(另一个指令)而修改过的。
在此先感谢您的帮助。