Simple prime number generator

tux4life 0 Tallied Votes 179 Views Share

This prime number generator is based on Eratosthenes' sieve, the found prime numbers are written to a file (you can specify it's name as a command line argument, as well you can specify the prime number upper bound (e.g: if you specify 500 as upper bound, the program will find all prime numbers which are in range of 2-500) :)

/**
Mathias Van Malderen (tux4life)
*/
#include <iostream>
#include <fstream>
#include <new>
#include <cstdlib>

int main(int argc, char *argv[])
{
    if(!(argc==3)) {
        std::cout << "Syntax: prime <number> <output_file>" << std::endl;
        return 1;
    }

    std::ofstream outfile;
    outfile.open(argv[2]);
	
    if(!outfile.is_open()) {
        std::cout << "Error opening output file!" << std::endl;
        return 1;
    }

    unsigned long long i, j, count = 0;
    const unsigned long long maxprime = atoll(argv[1]);
    char *sieve = new(std::nothrow) char[maxprime+1]; // allocate memory
	
    if(!sieve) {
        std::cout << "Memory allocation error!" << std::endl;
        return 1;
    }

    for(i=2; i<=maxprime; i++) // initialize our sieve
        sieve[i]=1;

    for(i=2; i*i<maxprime; i++)
        if(sieve[i])
            for(j=i*i; j<=maxprime; j+=i) // strip out all multiples
                sieve[j]=0;

    // write the prime numbers to the output file			
    for(i=2; i<maxprime; i++) {
        if(sieve[i]) {
            outfile << i << "\n";
            count++;
        }
    }

    outfile << std::endl << "Total prime numbers: " << count;
    outfile.close();

    std::cout << "Total prime numbers found: " << count << std::endl;
    std::cout << "Results are saved in: " << argv[2] << std::endl;

    delete sieve; // deallocate memory
    return 0;
}