Printing Prime Numbers in Assembly


I'm trying to print prime numbers from 1-100 in assembly, but not only is my code printing out extra numbers, but also excluding some prime numbers.

Here is my main procedure:

mov min, 1

  inc min                    ; min++
  mov eax, min
  cmp eax, max               ; compare 2 and 100
  je  next                   ; jump unless 2 < 100

  call isPrime               ; check if prime
  cmp ecx, 0
  jne loopStart 
push eax
  call printPrime            ; print the prime numbers
pop eax
  jmp loopStart

  next:                      ; once max is 100

  push 0                          
  call ExitProcess

And my isPrime is:

mov prime, 0                 ; set as true
mov ecx, prime                  
mov k, 2                     ; reset k 

mov edx, 0                   ; clear edx
div num                      ; n/2
mov edx, 0                   ; clear edx again

cmp ecx, 0                   ; while prime
jne E                        ; if prime isnt true

cmp eax, k                   ; k<=n/2
jl E

mov eax, min
div k
cmp edx, 0                   ; check for remainder
jne kAdd

mov prime, 1                 ; set as false
jmp E

inc k
jmp start

mov ecx, prime
mov eax, min

isPrime endp

It prints out: 2 3 5 7 13 15 19 21 25 31 33 37 39 43 49 51 55 57 61 63 67 73 75 79 81 85 91 93 97 99

Is the fact that most of the extra numbers are divisible by 3, 5, and 7 (which are all prime numbers) have to do with something?


You're not properly resetting EDX inside the loop in isPrime. That is, before div k you need to put a mov edx,0 or xor edx,edx.

Also, I'm not sure where num comes from in div num at the beginning of the function(?). The comment says that you're dividing by 2, so did you mean div k?

And there's some unnecessary code in your program. Like this check:

cmp ecx, 0                   ; while prime
jne E                        ; if prime isnt true

If you look at the rest of the code it should become clear that ECX never will have any other value than zero at that point.

By : Michael

This video can help you solving your question :)
By: admin