Prime numbers

I've got to display all of the prime numbers in the [a,b] interval,where a and b are introduced from the keyboard.

1
2
3
4
5
6
7
8
9
10
11
12
13
      int a,b,n,i,k=0,j;
    cout<<"a=";cin>>a;
    cout<<"b=";cin>>b;
    if(a<b)
    {
        for(i=a;i<=b;i++)
        {
            n=i;
            for(j=1;j<=n;j++)
                if(n%j==0)k++;
                if(k==2)cout<<i<<endl;
        }
    }

I don't understand why this doesn't work.Can I please receive the correct code for this exercise?Please do not use functions.
Last edited on
1) what is k doing? Why isnt it just if !n%j print?
2) you only have to go to sqrt n+1 in the inner loop, which will become slow in a hurry.
3) n is useless, just use i.

I am here just to say about efficiency. This is not efficient algorithm. Search google for Sieve of Eratosthenes, which is efficient for finding primes in given interval.
Topic archived. No new replies allowed.