Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that generates all prime numbers between 2 and 1000, using the S

ID: 3569745 • Letter: W

Question

Write a program that generates all prime numbers between 2 and 1000, using the Sieve of Eratosthenes method. You can find many articles that describe the method for finding primes in this manner on the Internet. Display all the prime values.

This is what I have so far:

.386
.model flat, stdcall
.stack 4096
ExitProcess proto, dwExitCode:dword

FIRST_PRIME = 2
LAST_PRIME = 1000;

.data
sieve BYTE LAST_PRIME SUP(0)
str1 BYTE "This number is a prime number", 0dh, 0ah, 0

.code
main proc

   mov esi, FIRST_PRIME

   .WHILE esi < LAST_PRIME
   .IF sieve[esi] == 0
   call CrossOutMultiples
   .ENDIF
   inc esi
   .ENDW

mov eax, esi
add esi, eax

L1:   cmp   esi, LAST_PRIME
   ja   L2
   mov   sieve[esi], 1
   add   esi, eax
   jmp   L1

L2: mov esi, offset str1       ; Display the prime numbers
   call WriteString

   invoke ExitProcess, 0
main endp
end main

Explanation / Answer

INCLUDE Irvine32.inc

PrintPrimes PROTO,
count: DWORD; number of values ??to display

FIRST_PRIME = 2
LAST_PRIME = 1000;

.data
commaStr BYTE ",", 0

.data?
sieve BYTE LAST_PRIME DUP (?)

.code
main PROC
; Initialize the array to zeros
mov ecx, LAST_PRIME
mov edi, OFFSET sieve
mov al, 0
cld
rep stosb


mov esi, FIRST_PRIME

.WHILE Esi <LAST_PRIME
.IF Sieve [esi * TYPE sieve] == 0; is current entry prime?
call MarkMultiples; yes: mark all of its multiples
.ENDIF
inc esi; move to next table entry
.ENDW

INVOKE PrintPrimes, LAST_PRIME; display all primes found

exit
main ENDP

; ------------------------------------------------- -
MarkMultiples PROC
;
; Mark all multiples of the value passed in ESI.
; Notice we use ESI as the prime value, and
; Take advantage of the "scaling" feature of indirect
; Operands to locate the address of the indexed item:
; [Esi * TYPE sieve]
; ------------------------------------------------- -
push eax
push esi
mov eax, esi; prime value
add esi, eax; start with first multiple

L1: cmp esi, LAST_PRIME; end of array?
ja L2; yes
mov sieve [esi * TYPE sieve], 1; no: insert a marker
add esi, eax
jmp L1; repeat the loop

L2: pop esi
pop eax
ret
MarkMultiples ENDP


; ------------------------------------------------- -
PrintPrimes PROC,
count: DWORD; number of values ??to display
;
; Display the list of prime numbers
; ------------------------------------------------- -
mov esi, 1
mov eax, 0
mov ecx, count

L1: mov al, sieve [esi * TYPE sieve]
.IF Al == 0
mov eax, esi
call WriteDec
mov edx, OFFSET commaStr
call WriteString
.ENDIF
inc esi
loop L1

ret
PrintPrimes ENDP


END main

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote