Sieve of Eratosthenes prime numbers up to a million c++ -


so need code. reason keeps crashing when enter number past 500,000. here exact assignment.

implement sieve of eratosthenes , use find prime numbers less or equal 1 million. use result prove goldbach's conjecture integers between 4 , 1 million, inclusive.

implement function following declaration:

void sieve(int array[], int num); 

this function takes integer array argument. array should initialized values 1 through 1000000. function modifies array prime numbers remain; other values zeroed out.

this function must written accept integer array of size. must should output primes numbers between 1 , 1000000, when test function may on array of different size.

implement function following declaration:

void goldbach(int array[], int num); 

this function takes same argument previous function , displays each integer between 4 , 1000000 2 prime numbers add it.

the goal here provide efficient implementation. means no multiplication, division, or modulus when determining if number prime. means second function must find 2 primes efficiently.

output program:

all prime numbers between 1 , 1000000 , numbers between 4 , 1000000 , 2 prime numbers sum it.

do not provide output or session record project!

and here have far. if me great.

#include <iostream> using namespace std;  void sieve (int array[], int num);  int main() {     int num;     cout << "enter number calculate to." << endl;     cin>> num;     if ( num < 2 )         return 0;      int array[num];     array[0]= array[1]= 0;     ( int i= 2; < num; ++i )         array[i]= i;     sieve(array,num);     (int i=0; i<num; i++)         if (array[i] > 0)             cout << array[i] <<" "<<endl;     cout<<endl;      return 0; }  void sieve( int array[], int num ) {     ( int i= 0; < num; ++i )     {         if ( array[i] != 0 )         {             ( int j= i+i; j < num; j += )             {                 array[j]= 0;             }         }     } } 

the reason why code crashes you're using vla allocation array here

int array[num]; 

it's used allocate num int elements of stack, small hold million of int values.

you should note it's not standard c++ feature, extension provided number of compiler implementations.

to fix there 3 alternatives:

  1. you configure stack size used program big enough hold number of int elements (this os dependend)
  2. you use std::vector<int> array(num); instead, allocates these elements on heap memory
  3. you allocate necessary memory on heap using int* array = new int[num]; , delete [] array; @ end of program (i wouldn't recommend solution, because it's prone make silly mistakes regarding proper memory management)

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -