Blair McKinney
Blair McKinney

Reputation: 61

Why does this procedure fail without "mov edx, 0"?

I was working on an assignment to take a user provided integer and determine if it is prime. The program I wrote worked fine I just don't exactly understand why I need to set edx to 0 every cycle.

    ;--------------------------------------------------------------------------
IsPrime PROC
;
; This determines if the integer is a prime
;--------------------------------------------------------------------------
mov ebx,eax                 ;Copying eax -> ebx
sar eax,1                   ;Arithmetic shift right to make eax = eax/2
mov esi,eax                 ;Setting esi = half of our number
mov ecx,1

    isPrimeLoop:
        add ecx, 1          ;increments ecx, starts at 2
        cmp ecx,esi
        ja itsPrime

        mov edx,0
        mov eax,ebx
        div ecx             ;dividing to see if it has a remainder or not
        cmp edx,0
        jz itsNotPrime
        jmp isPrimeLoop

    itsNotPrime:                ;displays results for numbers that are not prime
        mov eax,ebx
        call WriteDec
        mWrite " is not a prime number it is divisible by "
        mov eax,ecx
        call WriteDec
        call Crlf
        jmp endPrime



    itsPrime:                   ;displays results for numbers that are prime
        mov eax,ebx
        call WriteDec
        mWrite " is a prime number."
        call Crlf
        jmp endPrime

    endPrime:
ret
IsPrime ENDP

Upvotes: 1

Views: 1865

Answers (1)

Joshua
Joshua

Reputation: 43280

Because div divides edx:eax by whatever. The result lands in eax and the remainder in edx. If the result doesn't fit in eax (likely if edx contains garbage), an interrupt is raised, which the OS translates into SIGFPE.

Upvotes: 2

Related Questions