Skip to content

Primality test

C++ loop with early return

Same task in: GoTypeScriptRust

Flowchart (ISO 5807)

YesNoYesNoStartInput nn < 2Return falseEndi = 2, i² ≤ n, i = i + 1n mod i = 0Return falseEndReturn trueEndFigure 1 — isPrime

Source code

C++
bool isPrime(int n) {
    if (n < 2) return false;
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) return false;
    }
    return true;
}

The editor opens with this code — change it and the chart redraws.

Language
C++
Constructs
loop with early return
Topic
Algorithms
Formats
Word, Visio, draw.io, PDF, SVG

Related examples