assemblyx86intelirvine32

x86 Assembly how to use DIV instruction and loop to check if integer is prime


I've created a procedure that will print all the prime numbers up to the user input. However, some of the output values are not prime such as 15, 21 etc. If I begin the program with 15, it will not output it as prime, so it must be my DIV segment or loop. Any help is much appreciated.

.code
main proc



mov ecx, 18             ;ecx is the loop counter
mov eax, 2              ;assume 2 is prime
L1:
    inc eax             ;start with value 3
    call isPrime
    loop L1


invoke ExitProcess,0
main endp

isPrime PROC          ;Procedure
push eax
push ecx
mov valEntered, eax
mov ogCounter, ecx


mov edx, 0            ;check if 
                      ;value divisible by 2
mov eax, eax
div divisor0          ;divisor0 = 2
mov eax, edx
cmp eax, 0
jz no   


mov ecx, valEntered         ;ecx loop 
                            ;counter

L2:              ;check if 
                 ;value divisible by >= 3
mov eax, iStart  ;iStart = 3
mul iStart
cmp valEntered, eax
jl yes

mov edx, 0
mov eax, valEntered
div iStart      ;iStart = 3
mov eax, edx
cmp eax, 0
jz no       
add iStart, 2   ;iStart += 2
loop L2
jmp no


yes:                ;output prime number
mov eax, valEntered
call WriteInt
call Crlf
mov ecx, ogCounter
pop ecx
pop eax
ret

no:                ;continue to next int
mov ecx, ogCounter
pop ecx
pop eax
ret

isPrime ENDP
end main

Solution

  • You change iStart when checking for a prime but you never reset it back to 3 for the next check.