Reputation: 33
Having a slight error in this program. It's a simple program that allows the user to input a number higher than 2 and determine if it's prime or not. It works fine expect for the numbers of 3 and 4. 3 is said to be not a prime and 4 is a prime. I'm simply showing the code for the calculations.
;ecx = divisor, esi = max divisor, edx = remainder, eax = quotient
mov ebx, eax
shr eax, 1
mov esi, eax ;Max divisor value
mov ecx, 1
isPrime:
inc ecx
cmp ecx, esi
je Prime
mov edx, 0
mov eax, ebx
div ecx
cmp edx, 0
jz NotPrime
jmp isPrime
I'm not sure if the shr
might have something to do with the error. Any explanations? I'm trying to avoid making jumps just for those values.
Thank you for your time.
Upvotes: 0
Views: 513
Reputation: 14409
je Prime
is wrong. The value of ESI
is the half of EAX
(rounded down). If EAX
is 3, then ESI
will become 1. ECX
starts effectively with 2 (mov ecx, 1
inc ecx
). So it will loop over the whole 32 bit range before it will be equal to ESI
. When ECX
becomes 3 then the loop will break to NotPrime
.
If EAX
==4, the loop will break to Prime
at once: the first ECX
is 2 and ESI
is 2.
Remedy: Change je Prime
to ja Prime
.
Upvotes: 2