views:

129

answers:

2

Hi,

I am new to assembly language. I have written a program for taking an input and then displaying whether the number is prime or not.

Here is my source code.

.intel_syntax noprefix

.include "console.i"


.data

        Num:    .long 0

.text

        ask:    .asciz "Enter a +ve number : "
        ansp:   .asciz " is prime."
        ans:    .asciz " is not prime."

_entry:

        Prompt ask
        GetInt Num

        mov eax,Num # store Number in eax
        #mov ecx,0   # Reset ecx to 0
        mov ecx,0    # Reset ecx t0 2 for dividing.
        cdq

1:      inc ecx       # increment ecx
        mov ebx,eax   #backup eax
        Div ecx       #Divide eax by ecx

        cmp edx,0     #if remainder is zero num is not prime
        je 2f
        mov edx,0     #reset edx to 0
        mov eax,ebx   #reset eax to Num

        cmp eax,ecx   if ecx is less than number.
        jl 1b


        #Prime
        PutInt Num
        Prompt ansp
        jmp 3f

2:      #Not Prime
        PutInt Num
        Prompt ans

3:      PutEol
        ret

.global _entry

.end

When ever I run the program it always displays it is not a prime number.

For example if I input 7 it displays 7 is not prime.

I am using Intel x86 Architecture and devloping it on Ubuntu.

Edit 1 : According to Darron, I have initalized ecx register to 1 and then incremented ecx to 1 so that it starts the loop from 2.

But the problem is when I enter 9 it shows me 9 is prime. I don't know what's wrong with my logic.

Edit 2 : I am storing my number in eax, and then I divide it by ecx and then finally check if the reaminder is zero in edx register.

Thanks.

+8  A: 

You start by dividing by 1. Even prime numbers are divisible by one.

Darron
Oh, I am really stupid sometimes. I will give it a try tomorrow in college.
Searock
I have tried your advice and have started ecx from 2. But when I enter 9 or say 21 it shows number is prime. Can you help me with the logic, please ?
Searock
+1  A: 

I have solved my problem using gdb(GNU Project Debugger).

In my logic I was dividing the number up to the given number, for example if I input 15 the logic was dividing the number upto 15, but for prime numbers we have to divide up to number -1 ie(15-1).

Here is my updated block of loop.

1:      inc ecx 
        mov eax,ebx 
        Div ecx

        cmp edx,r
        je 2f

        mov edx,0
        mov eax,ebx
        Sub eax,1
        cmp ecx,eax
        jl 1b
Searock