title: Sieve of Eratosthenes x86 Assembly
body: <p>I am new to assembly, trying to implement Sieve of Erathothenes, I have the code but it only works between 1 and 600, for some reason it goes haywire when I put n=1000, here is the complete code, any help will do.</p>
  
  <pre><code>Include Irvine32.inc
  n=1000
  
  .data
  prime DWORD n DUP(?)
  
  .code
  main PROC
          mov ecx,n       ;initialize ecx to 1000
          mov esi, OFFSET prime
  ;--------------------------------------------------------
  ;   Initialize Array with 1's
  ;--------------------------------------------------------
  FillArray:  mov eax,1
          mov [esi],eax
          mov eax,[esi]
          add esi,TYPE DWORD              ;4 to jump to the next index
          loop FillArray
  
      mov ebx,8
      mov edx,0
      mov ecx,n
      mov ebp,2
      mov esi,0
  ;----------------------------------------------------------------
  ;   Sieve
  ;----------------------------------------------------------------
  SIEVE:      mov eax,prime[ebx]
          mov edx,ebx
          mov edi,ebx
          add edx,edi                 ;j=i+i
          mov esi,ebp
          mov ecx,n
          sub ecx,ebp
          add ecx,2
          add ebx,TYPE DWORD
          cmp eax,1
          je FLIP
          inc ebp
          loop SIEVE
          jmp K
  
  FLIP:       mov eax,0
          mov prime[edx],eax
          add edx,edi
          cmp esi,n
          jg SIEVE
          add esi,ebp
          loop FLIP
  
  K:
  
      mov esi, OFFSET prime
      mov ecx,n
      sub ecx,2   
      mov ebx,1
      mov edx,8           ;Start checking from index of second element
  
  PRINT:  mov eax,prime[edx]          ;
          add edx,TYPE DWORD
          inc ebx
          cmp eax,1
          jne H
          mov eax,ebx
          call WriteDec
          call Crlf
          loop PRINT
          jmp D
  H: loop PRINT
  D:
      exit
  
  main ENDP
  END main
  </code></pre>