Start New Discussion within our Software Development Community

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;[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

    for(i=2; i*i<maxprime; i++)
            for(j=i*i; j<=maxprime; j+=i) // strip out all multiples

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

    outfile << std::endl << "Total prime numbers: " << count;

    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;
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.