Start New Discussion within our **Software Development Community** # Prime Number Generator with unmatched speed.

```
//PrimeGen_v4 by BevoX 08/02/2009
//#include <new> //uncomment this, or try with new.h if you get compiler errors beacuse of ba.what()
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <fstream>
using namespace std;
class Primes
{
public : Primes( const unsigned int & );
~Primes(){ delete []array; };
void FindPrime();
void WriteOut();
private : unsigned int *array, _size, max_divisor, n, step;
const unsigned int end;
ofstream out_file;
};
int main()
{
unsigned int end_param;
cout << "PrimeGen_v4 by BevoX" << endl << "Enter the last element: ";
cin >> end_param;
// don't try to feed it with negative numbers, it can't handle them
if( end_param < 2 )
{
cout << "Invalid interval!" << endl;
cin.ignore( 1,'\n' );
cin.get();
exit(1);
}
cout << " * WORKING.." << endl;
Primes Alpha( end_param );
Alpha.FindPrime();
Alpha.WriteOut();
cout << " * FINISHED" << endl << "The results can be found in the 'Primes.txt' file." << endl;
cin.ignore( 1,'\n' );
cin.get();
return 0;
}
Primes::Primes( const unsigned int & _end_param ) : end( _end_param ) // constructor
{
if( ( end % 2) == 0 ) _size = end / 2; // even numbers won't be initialized -> half size
else _size = ( end / 2) + 1;
try{ array = new unsigned int [ _size ]; } // allocates memory
catch( bad_alloc &ba )
{
cout << "! ERROR : " << ba.what() << endl;
cin.ignore( 1,'\n' );
cin.get();
exit(1);
}
n = 1;
for( unsigned int i = 0; i < _size; i++ ) //occupies array, with odd numbers
{
array[i] = n;
n += 2;
}
}
void Primes::FindPrime()
{
max_divisor = sqrt( (float)end );
step = 1;
do
{
n = array[ step ];
for( unsigned int i = step + 1; i < _size; i++ )
{
if( array[i] != 0 )
{
if( array[i] % n == 0) array[i] = 0;
}
}
step++;
while( array[ step ] == 0 )
{
step++;
}
}
while( n <= max_divisor );
}
void Primes::WriteOut()
{
out_file.open( "Primes.txt" );
if( out_file )
{
for( unsigned int j = 0; j < _size; j++ )
{
if( array[j] != 0 ) out_file << array[j] << " ";
}
out_file.close();
}
else
{
cout << "! ERROR -- Unable to create FILE !!!" << endl;
cin.ignore( 1, '\n' );
cin.get();
exit(2);
}
}
```