Generate prime numbers in C++ with the Sieve of Eratosthenes by marking every composite multiple and printing the numbers that remain unmarked.

For an upper limit N, the program below prints every prime from 2 through N, together with the count, sum, and largest prime. A prime is a whole number greater than 1 with exactly two divisors: 1 and itself.

how to generate prime numbers in c++
How to Generate Prime Numbers in C++: Sieve Code

What the C++ generator produces

The program takes one integer, N, and treats it as an inclusive upper bound. It creates a Boolean status for each number, marks composite numbers, and scans the statuses in ascending order. Because the output comes from a single scan, the primes are automatically sorted and cannot contain duplicates.

The sieve is efficient for bulk generation because it reuses information across the range. Its marking stage takes about O(N log log N) time, while the Boolean array uses O(N) space. This is a better fit for producing a complete list than checking every candidate independently.

Approach Result Best fit
Sieve of Eratosthenes Every prime through a limit N Ranges, reference lists, and bulk test data
Trial-division check Whether one candidate is prime A single number or a very small collection

Trial division repeatedly tests a candidate for small factors. The sieve instead removes multiples of each confirmed prime, so later numbers benefit from earlier work. For a visual explanation of that marking process, see how the Sieve of Eratosthenes removes composite numbers.

Generate primes up to N in C++

  1. Read N as an integer. If the input operation fails, display an error and stop; if N is below 2, report that the range contains no primes.
  2. Create a Boolean vector with N + 1 entries and initialize every status to true. Set the entries for 0 and 1 to false because neither number is prime.
  3. Visit candidate values p from 2 while p × p is no greater than N. When p is still marked as prime, mark p × p, p × p + p, and the remaining multiples of p as composite.
  4. Scan every number from 2 through N. Print each number whose status remains true, adding spaces only between results.
  5. Track the number of printed primes, their sum, and the most recently printed value. After the final prime, the most recent value is also the largest prime in the range.

Starting each marking sequence at p × p avoids redundant work. For example, a multiple of p smaller than p × p has already been removed by a smaller prime factor. Using a long long value for the multiplication and multiple counter also prevents intermediate overflow in the square calculation.

Complete C++ program

Save the following as primes.cpp. It uses only standard C++ headers and includes the list plus three summary values in its console output.

#include <iostream>

#include <vector>

#include <cstddef>

int main() {

int N;

std::cout << "Enter the upper limit: ";

if (!(std::cin >> N)) {

std::cerr << "Please enter an integer.\n";

return 1;

}

if (N < 2) {

std::cout << "No prime numbers up to " << N << ".\n";

return 0;

}

std::vector<bool> isPrime(static_cast<std::size_t>(N) + 1, true);

isPrime[0] = false;

isPrime[1] = false;

for (int p = 2; 1LL * p * p <= N; ++p) {

if (isPrime[p]) {

for (long long multiple = 1LL * p * p;

multiple <= N;

multiple += p) {

isPrime[multiple] = false;

}

}

}

bool first = true;

int count = 0;

long long sum = 0;

int largest = 0;

std::cout << "Prime numbers up to " << N << ":\n";

for (int number = 2; number <= N; ++number) {

if (isPrime[number]) {

if (!first) {

std::cout << ' ';

}

std::cout << number;

first = false;

++count;

sum += number;

largest = number;

}

}

std::cout << "\nCount: " << count << '\n';

std::cout << "Sum: " << sum << '\n';

std::cout << "Largest: " << largest << '\n';

return 0;

}

The outer loop stops when p × p passes N. This is sufficient because every composite number has a factor no greater than its square root, so every composite within the range is marked before the final scan. The long long sum variable provides additional range for the total, while the outer multiplication uses 1LL to evaluate the square in a wider integer type.

Compile and run the C++ program

  1. Save the source in a file named primes.cpp, and open a terminal in the same folder.
  2. Compile the file with g++ -std=c++17 -O2 -Wall -Wextra primes.cpp -o primes. The optimization flag improves performance, while the warning options help reveal common compile-time issues.
  3. Run ./primes on Linux or macOS, or run primes.exe in Windows Command Prompt.
  4. Enter the desired upper limit when the program asks for it. The program prints the complete list followed by the count, sum, and largest prime.

For one worked run, enter 30. The output is:

Prime numbers up to 30:

2 3 5 7 11 13 17 19 23 29

Count: 10

Sum: 129

Largest: 29

The summary calculation is 2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23 + 29 = 129. Notice that the endpoint is included only when it is prime, and 1 never appears in the output.

Check the C++ output with a browser generator

When you want a reference list without compiling a program, use the Prime Number Generator. Its stated function is to generate numeric lists and summaries rather than C++ source code, so it fits as an output-checking step for your program.

  1. Choose Primes up to N to list every prime less than or equal to your limit, or choose First N primes to request an exact fixed count.
  2. Type your value for N into the input box, then press Generate primes or hit Enter.
  3. Read the prime list, total count, sum of all primes, and largest prime. The complete list can also be copied with one click.

The browser tool uses the Sieve of Eratosthenes under the hood. Its “First N primes” mode uses a proven upper bound for the requested prime so that the sieve knows how far to search. Processing happens in the browser: nothing is uploaded, and there is no server-side queue or count limit. There are still browser-mode ceilings, however. “Primes up to N” accepts N up to 10,000,000, while “First N primes” accepts N up to 100,000. Larger values are blocked to keep the tool responsive.

Match the requirement to the correct output mode

Requirement Meaning of N Correct workflow
Every prime at or below a limit Inclusive upper bound Run the C++ listing and compare it with “Primes up to N”
Exactly a fixed number of primes Requested count Use “First N primes”
A console program for an assignment Upper limit in the supplied listing Save, compile, run, and test the source directly

This distinction is important: the C++ program in this guide uses N as an upper limit and does not promise that the output will contain exactly N primes. If an assignment instead asks for the first N primes, use the generator’s fixed-count mode and compare its ordered list with the expected sequence.

Handle edge cases and save the results

  • Limits below 2: The range contains no primes, so the program prints a message and exits without attempting to create the sieve.
  • 1 is not prime: It has only one divisor. The number 0 is not prime either.
  • 2 is special: It is the smallest prime and the only even prime.
  • The endpoint is inclusive: N is printed when it is prime because the final scan includes N.
  • The output stays ordered: The scan proceeds from 2 through N, so the values appear in ascending order.
  • Large limits consume memory: The Boolean array grows linearly with N. The browser generator’s separate mode limits do not automatically apply to a locally compiled C++ program.

To save the console output on a system with shell redirection, run ./primes > primes.txt. The text file will contain the prime list and the three summary lines, which makes it easy to diff against a reference list or inspect later.