Reputation: 11
I am a beginner in x86 assembly. Below is my code for my prime number program- so far. This code isn't outputting '0' for NOT prime numbers as it should - it is however outputting '1' for all numbers. Any help would be really appreciated. The program is supposed Output '1' if the user input a prime number and Output '0' if the user input was not prime.
My first x86 programs have been very difficult to read and deeply understand. How can I gain deeper insight of the code and also be able to follow how it functions better? I do know what all the instructions mean individually but not so well in this lengthy code.
format PE console
entry start
include 'win32a.inc'
section '.text' code readable executable
start:
;using eax,ebx,ecx,edx,esi
call read_hex
;Move user input into ecx for use in the countdown Loop
mov ecx,eax
coundown:
;countdown for the division circuit of user's input
dec ecx
jz print_zero
mov esi,ecx
sub esi,2
jz print_zero
jnz check
check:
;loop of division circuit(for dividing 'user input' by all the numbers from 1 to the input value.)
mov edx,0
div ecx
mov ebx,0
sub ebx,edx
jnc print_one
jz print_zero
jmp countdown
print_zero:
mov eax,0
call print_eax
jmp outside
print_one:
mov eax,1
call print_eax
outside:
; Exit the process:
push 0
call [ExitProcess]
include 'training.inc'
Upvotes: 1
Views: 250
Reputation: 15144
One problem is that the decrement
label seems to call some other code that you did not provide, rather than what’s the comment says is supposed to be the top of the loop. You might have meant to jump back to check
. There are many others: if you fix that, you’ll now stop when the decremented value reaches 0. However, that means you’ll trial-divide by 1, find that 1 is indeed a factor, and all numbers will incorrectly seem to be composite. If you solve that, I’m pretty sure you didn’t mean to write the tests in countdown
that way, but I can’t tell what it’s supposed to be doing instead.
I’m not sure whether you’re interested in suggestions for efficiency. If not, skip the rest of this post. One simple one would be to use the theorem that any composite number has at least one factor less than its square root to count up and stop counting when i×i > n. Furthermore, you can strength-reduce this multiplication to addition by keeping track of both i and i² and updating it with the formula (i+2)² = i² + (4·i + 4). Another quick refinement is to use the Chinese Remainder theorem to show that any number congruent to 0, 2, 3 or 4 (mod 6) is composite, so after testing 5, you can alternate between adding 2 (to get the next number congruent to 1) and adding 4 (to get the next number congruent to 5). Any prime factor must be in this sequence.
Upvotes: 1