'Assembly: Modify a odd number generator into a prime number generator
I have written a PROC to find all odd numbers. I want to transition the existing code into a prime number generator.
The intent of the entire program is to take a number between 1-200 input by the user and display all the odd numbers up to and potentially including that number (if its odd)
I want to evolve it into generating the prime numbers between 1-200 based on the user input.
I have omitted most of the code but the showPrime
its sub procedures and isPrime
PROCS have been added below.
showPrimes PROC
;-------------------------------------------------------------------------------------------
;Calculates and displays the prime numbers up to and including the userNum if its also prime
;10 results per line
;recieves: userNum, count, bPrime
;--------------------------------------------------------------------------------------------
mov eax, 2
call Crlf
call WriteDec ; print 2
mov edx, OFFSET spaces
call WriteString ; print spaces
inc colNum
cmp userNum, 1 ; If userNum = 1, all done, so exit
je primesDone
inc count ; else, increase count & continue
mov esi, OFFSET arr ; point to array
mov [esi], eax ; move 2 to first index
inc arrsize ; inc size
; Starting with 3, loop thru odd numbers using ecx until count > userNum
mov ecx, 3
LoopPrimes:
mov eax, count
cmp eax, userNum
jg PrimesDone ; while count <= userNum
pushad
call isPrime ; call isPrime procedure
popad
cmp bPrime, TRUE ; if isPrime(ecx)
jne AddTwo ; jump to end of loop
; If ecx = prime
mov esi, OFFSET arr
mov eax, 4
mul arrsize
add esi, eax
mov [esi], ecx
inc arrsize
mov eax, [esi]
cmp colNum, 10
jle SameLine
mov colNum, 1 ; if colNum > 10 reset to 1
call Crlf ; start new line
SameLine:
mov eax, ecx
call WriteDec ; print prime
mov edx, OFFSET spaces
call WriteString ; print spaces
inc colNum ; increment column number
inc count ; increment count
; Else
AddTwo:
add ecx, 2 ; increment ecx to next odd num
jmp LoopPrimes ; loop
PrimesDone:
call Crlf
ret
showPrimes ENDP
isPrime PROC
;------------------------
;Verifies number is prime
;receives: factor, bPrime
;------------------------
mov ebx, 0 ; ebx = current array index
mov esi, OFFSET arr ; esi = ptr to index in ebx
mov check, ecx ; number to find out if prime
cmp ecx, 3
je PrimeNum
PrimeLoop: ; divide check by every number in array
cmp ebx, arrsize ; while ebx < arrsize and check % factor != 0
jge PrimeNum ; reached end of array, no divisors found, so it's prime
mov ecx, [esi] ; move value
mov edx, 0
mov eax, check
div ecx
cmp edx, 0
je NotPrime ; if remainder = 0, not prime
add esi, 4 ; else continue searching array
inc ebx
jmp PrimeNum
PrimeNum:
mov bPrime, TRUE
ret
NotPrime:
mov bPrime, FALSE
ret
isPrime ENDP
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|