problem with bool and Arrays combined

Hi, Im trying to create Sieve of Eratosthenes to find prime numbers up to some predefined integer n

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
#include <iostream>
using namespace std;

int main()
{
    int n;
    cin >> n;
    
    int size = n - 1;
    bool* isPrime;
    isPrime = new bool[size];
    
    //Declares all integers from 2 to n to be true in bool isPrime
    for ( int i = 2; i <= size; i++ )
        isPrime[i] = true;
   
   //if 2 is Prime, deletes all multiples of 2, etc
    for ( int i = 2; i <= size; i++ )
    {
        if ( isPrime[i] )
        {
             for ( int j = i ; j <= size; j++ )
             {
                 isPrime[i * j] = false;
             }                 
        }
    }
    
    //Prints out all integers with isPrime = true.
    for ( int i = 2; i <= size; i++ )
       {
              if (isPrime[i])
                 cout << i << " ";
       }
    
    system("PAUSE");
    return 0;
}
        


Problem is I cant get it to run at all for values of n more than 20. more than 20 crashes the program.
For values less than 20, it displays the prime numbers, but the program still crashes.
Any help is appreciated. Thanks!

edit***
Was just about to fall asleep then i thought of the solution! I solved it!
Program crash because i had assign bool data to values more than the specified array.
just needed to add an if i*j > size, break;
Thanks !!!
Last edited on
Topic archived. No new replies allowed.