liveBook · Manning

Prime number

As explained in Learn C++ by Example

A prime number is a positive integer greater than one that has no positive divisors other than one and itself.

A prime number is a positive integer greater than one with exactly two positive divisors: one and itself. section 3.3.1

A practical primality check handles 2 and 3 directly, rejects values at most 1 and multiples of 2 or 3, then tests possible factors from 5 through the square root. section 3.3.1

Random prime guessing game

Generate integers from 1 to 99,999 and keep rejecting candidates until is_prime accepts one. Use the result as the target in a guessing game that reports whether guesses are too small or too large. section 3.3 section 3.3.3

Listing 3.11 Function to check whether a number is prime
bool is_prime(int n)
{
    if (n == 2 || n == 3)                      #1
        return true;
 
    if (n <= 1 || n % 2 == 0 || n % 3 == 0)    #2
        return false;
 
    for (int i = 5; i * i <= n; ++i)           #3
    {
        if (n % i == 0)
            return false;                      #4
    }
 
    return true;                               #5
}

Inspect the complete C++ primality-checking function, including modulo tests, the square-root stopping condition, and early returns. section 3.3.1

How Learn C++ by Example covers it

How deep it goes
Explains a tested modulo algorithm through square-root bounds, while deferring further optimizations and the sieve of Eratosthenes.
Examples
Demonstrates primes through 2, 3, 4, 6, and 35, then applies them to a five-digit guessing game.
What it assumes
Assumes basic integer arithmetic and modulo while introducing factors, divisibility checks, and rejection sampling practically.
What you can do after
Build a C++ primality predicate and use rejection sampling to generate prime game targets.
How it connects
Connects prime numbers with divisibility, factors, square roots, random number generation, and rejection sampling.

Also explained in

Compare how 5 books explain prime number →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.