Prime numbers

Feb 1, 2015 at 7:48pm
Hello!I was trying to write a program that shows all the prime numbers smaller than n.However,something strange happens.When n is 10,for example,the program shows "2 5 7" (missing 3). If n is 100, the program shows all the prime numbers smaller than 100 except 3,5 and 7.What am I doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int n,j,i,t=1;
    cin>>n;
    for(j=1;j<n;j++)
       {t=1;
        if(j<=1||(j%2==0&&j!=2))
        t=0;
        else
        {
            for(i=3;i<=((int)sqrt((double)n));i=i+2)
                if (j%i==0){ t=0;
                            break;}
        }

        if (t==1)cout<<j<<endl;
      
       }
       
    return 0;
}
Feb 1, 2015 at 8:49pm
1
2
3
for(i=3;i<=((int)sqrt((double)n));i=i+2)
    if (j%i==0){ t=0;
                break;}

For every n that is higher than 3, this code will automatically leave out the number 3 (because i is initialized as 3, and if j is 3, the if loop will be true and t will be set to 0 so that j (which is 3) will not be printed out.


IMHO, this is a not a good prime number generator algorithm, but then again I can't see the idea in your head, so you might be on to something that I can't see.
Feb 1, 2015 at 10:12pm
In fact, it will leave out every prime number lower than square root of n.
That's why when you enter 100, you get all prime numbers except 3, 5, and 7 (since square root of 100 is 10).
Topic archived. No new replies allowed.