Prime numbers

Hello,

I wrote a program to print all the prime numbers between 1 and 100, see http://en.wikipedia.org/wiki/Prime_number

My problem is that it does not compile: Getting some errors like "stray 302 in program"

Here is the implementation

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
27
28
29
30
31
32
33
34
35
36
 #include<iostream>
#include<vector>

using namespace std;

int main()

{

 vector<int>primes;
 for (int i=3; i< 100; ++i)
{

   bool prime=false;


   for (int j=0;j<100 && primes[j]<i; ++j)
   {

     if (i % primes[j] != 0)
     {  
       prime=true; 
     }
   }

   if(prime)   
   {
     primes.push_back(i); cout << i << " "; 
             
   }

}

return 0;               
  
}
"stray" errors often occur when you copy paste code from somewhere and you get weird characters copied into your code. Often they are invisible so it's hard to spot.

Copy the code from your post and you will probably be able to compile, at least it worked for me.
Ok,

strange, now when I compiled I get this: Segmentation fault (core dumped)
The reason you get a segfault is because you try to access elements in the primes vector that doesn't exist.
I tried something like

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

#include<iostream>
#include<vector>

using namespace std;

int main()

{

   vector<int>primes;
   for (int i=3; i< 100; ++i) {

do {
    primes.push_back (i);
   }  while (i);


   bool prime=false;


   for (int j=0;j<100 && primes[j]<i; ++j)
   {

     if (i % primes[j] != 0)
     {  
       prime=true; 
     }
   }

   if(prime)   
   {
     primes.push_back(i); cout << i << " "; 
             
   }

}

return 0;               
  
}

	



It does not work though

Topic archived. No new replies allowed.