Learn / Worked program
Prime Finder
Prove a loop boundary, then reduce the work
What you will learn
- Console streams and complete-line input/outputProgram-local teaching concept
- Branch order, validated domains and early returnsLearn conceptDecisions and repetition
- Parameters, cohesive calculation functions and return valuesLearn conceptFunctions as interfaces
- Finite iteration domains and termination conditionsDecisions and repetitionProgram-local teaching concept
- Aliases for mutable or read-only existing objectsLearn conceptPointers and references
- Integer domains, truncation and arithmetic limitsLearn conceptValues and types
- Predicates and explicit true/false propositionsLearn conceptValues and types
- Integer remainder and divisibilityOperators and expressionsProgram-local teaching concept
- Complete-line parsing, bounded input and EOF terminationDebugging and code qualityProgram-local teaching concept
The complete source
main.cpp
#include <iostream>
#include <sstream>
#include <string>
bool readInteger(const std::string& prompt, int& value, int low, int high) {
std::string line;
while (std::cout << prompt && std::getline(std::cin, line)) {
std::istringstream input(line);
char extra = '\0';
if (input >> value && !(input >> extra) && value >= low && value <= high) return true;
std::cout << "Enter a whole number in [" << low << ", " << high << "].\n";
}
std::cerr << "Input ended before a valid integer was supplied.\n";
return false;
}
bool isPrime(int candidate) {
if (candidate < 2) return false;
// divisor <= candidate / divisor is equivalent to divisor^2 <= candidate,
// without multiplying two integers that could overflow.
for (int divisor = 2; divisor <= candidate / divisor; ++divisor) {
if (candidate % divisor == 0) return false;
}
return true;
}
int main() {
int limit = 0;
if (!readInteger("Inclusive prime limit (2 to 100000): ", limit, 2, 100000)) return 1;
int count = 0;
for (int candidate = 2; candidate <= limit; ++candidate) {
if (isPrime(candidate)) {
std::cout << candidate << ' ';
++count;
}
}
std::cout << "\nPrime count: " << count << '\n';
}
Source integrity
SHA-256 9f65ff67e6f5ce3123ce3e4dd991aefbe3b53f0f869745212ecbc6dfd97857c0. Display, copy and approved download use the same source.
What it does and why it was selected
The two prime labs solve the same useful task through different control-flow proofs. One stores an inverted integer flag; the other interprets where a divisor loop stopped. The canonical version names the proposition directly with bool isPrime and tests only divisors that can matter.
Actual execution
main validates an inclusive upper limit between 2 and 100000. For each candidate integer, it calls isPrime. That function rejects values below 2, then tries divisors beginning at 2. A zero remainder returns false immediately; reaching the loop’s end returns true. The caller prints accepted candidates and increments the count. For limit 20, the captured result is 2 3 5 7 11 13 17 19 and count 8. The count counts accepted candidates rather than divisor tests.
Mathematical or state model
If an integer n is composite, n=ab for integers a,b greater than one. Both factors cannot exceed sqrt(n), or their product would exceed n. Therefore checking divisors through sqrt(n) suffices. candidate%divisor==0 is evidence that divisor divides candidate exactly. The loop condition divisor<=candidate/divisor encodes divisordivisor<=candidate without creating a potentially overflowing product. Integer division is intentional here; for positive candidate and divisor it preserves this comparison.
Design and C++ mechanics
The primality function is a pure predicate, so main does not need to know how early exit works. Its return type matches the proposition being tested. For candidate 2, the loop never executes, and returning true is correct. For 4, divisor 2 is tested because the comparison includes equality, and the function returns false. Changing <= to < would incorrectly omit the square-root divisor for perfect squares. The bounded upper limit also ensures candidate++ will not overflow its int representation.
Historical differences and limits
Trial division is appropriate for an introductory program, but generating many primes scales much better with a sieve. The verification script intentionally uses a Python sieve as an independent oracle rather than copying this C++ algorithm into the test. The historical files compare an int candidate with a long-long user limit, which permits an input range the candidate cannot safely traverse. Their ordinary limit-20 outputs passed; that does not validate their extreme-input behavior.
Useful extensions
Compare elapsed work for trial division and a sieve with the same inclusive domain. Count remainder operations separately from the number of primes so the measurement has a clear meaning. Another extension is checking one user-supplied candidate, but adjust type limits and input bounds together rather than merely replacing int with a larger type.
Source-linked explanations
Follow each line reference to its marked source region. The explanations below are bound to the reviewed source hash and preserve the supplied teaching layers.
Input contract and end-of-file
main.cpp, lines 5–15 →Only validated whole integers are allowed to reach the Prime Finder calculation.
- Technical explanation
- getline consumes a complete line, then a temporary istringstream attempts the numeric conversion. After conversion, trying to extract extra detects a trailing non-whitespace character. Failure of that second extraction means no unwanted data remains. The local stream can fail without putting cin into the historical repeated-failbit state. A fresh local stream is created for every attempt. Low/high comparisons establish the caller’s domain, and exhausting cin ends the while condition and returns false.
- Syntax
- The && operators evaluate left to right and short-circuit: range tests run only after numeric extraction succeeds. !(input >> extra) intentionally treats no remaining non-whitespace character as success. A double& or int& parameter writes the accepted value into the caller’s variable.
- Effect on the program
- The caller checks the returned bool and returns exit status 1 on EOF before calculation. Rejected lines are followed by another prompt; valid lines reach the model exactly once.
- Common mistake
- Clearing a permanently exhausted input stream and retrying cannot create new input. Accepting a numeric prefix such as 550x would silently change the input contract.
- Deeper connection
- Reliable input separates parsing from physical or algorithmic validity: a valid number still must lie in this program’s supported domain.
A predicate with early disproof
main.cpp, lines 17–25 →The function’s name states the proposition returned.
- Technical explanation
- The function’s name states the proposition returned. Any divisor with zero remainder disproves primality and immediately returns false. Passing all divisors returns true. Values less than 2 are rejected before any divisor search, matching the mathematical definition.
- Syntax
- Values less than 2 are rejected before any divisor search, matching the mathematical definition.
- Effect on the program
- Values less than 2 are rejected before any divisor search, matching the mathematical definition.
- Common mistake
- The archived integer flag named isPrime actually stored 1 for composite. Inverted naming increases the chance of printing the wrong candidates.
- Deeper connection
- Read the program’s mathematical or state model
Include the square-root boundary safely
main.cpp, lines 21–24 →With positive integers, divisor<=candidate/divisor tests the square-root bound without divisor*divisor.
- Technical explanation
- With positive integers, divisor<=candidate/divisor tests the square-root bound without divisor*divisor. For candidate 4 and divisor 2, equality holds and the modulus test catches the factor. For candidate 2, the loop is skipped and returning true is correct.
- Syntax
- For candidate 2, the loop is skipped and returning true is correct.
- Effect on the program
- For candidate 2, the loop is skipped and returning true is correct.
- Common mistake
- Changing <= to < accepts perfect squares whose only small factor is exactly the root. Multiplying unrestricted ints to form the bound can overflow.
- Deeper connection
- Read the program’s mathematical or state model
Enumeration and counting are caller work
main.cpp, lines 31–37 →main enumerates candidates in ascending order and delegates the yes/no question.
- Technical explanation
- main enumerates candidates in ascending order and delegates the yes/no question. count increments only inside the successful predicate branch, not once per divisor or once per candidate. limit is inclusive, matching the prompt and test oracle.
- Syntax
- limit is inclusive, matching the prompt and test oracle.
- Effect on the program
- limit is inclusive, matching the prompt and test oracle.
- Common mistake
- A count of divisibility tests is not a count of primes. Keep instrumentation counters separate from result counters.
- Deeper connection
- Read the program’s mathematical or state model
Recorded input and output
Captured from the compiled canonical program in the supplied verification package. These are recorded terminal sessions, not an interactive browser runner.
Sample run
- Arguments
None- Recorded exit status
- 0
Program input
20
Program output
Inclusive prime limit (2 to 100000): 2 3 5 7 11 13 17 19 Prime count: 8
4 more recorded behavior and error cases
two
- Arguments
None- Recorded exit status
- 0
Program input
2
Program output
Inclusive prime limit (2 to 100000): 2 Prime count: 1
hundred
- Arguments
None- Recorded exit status
- 0
Program input
100
Program output
Inclusive prime limit (2 to 100000): 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 Prime count: 25
integer only
- Arguments
None- Recorded exit status
- 0
Program input
2.5 20
Program output
Inclusive prime limit (2 to 100000): Enter a whole number in [2, 100000]. Inclusive prime limit (2 to 100000): 2 3 5 7 11 13 17 19 Prime count: 8
eof
- Arguments
None- Recorded exit status
- 1
Program input
No standard input.
Program output
Inclusive prime limit (2 to 100000):
Error output
Input ended before a valid integer was supplied.
Build and run
From this folder, with a configured C++17 compiler:
g++ -std=c++17 -Wall -Wextra -Wpedantic main.cpp -o program
./programOn Windows GCC, build with -o program.exe and use .\program.exe. These are desktop examples; VS Code is an editor, the compiler builds an executable, and the terminal runs it.
Windows run command from the supplied metadata: .\program.exe.
Desktop compiler setup and platform limits. How headers and translation units fit together.
Verification and provenance
- Source inspected
- Compile verified
- Warning reviewed
- Behavior verified
- Sanitizer checked
Supplied evidence: 5 recorded behavior/error cases and 5 address/undefined-behavior sanitizer cases for this exact source. These are tested cases, not an exhaustive correctness claim.
Recorded compiler: g++ (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0.
LeakSanitizer: disabled because unavailable under runtime tracing. Windows/MSVC and macOS execution are not certified by this evidence.
Source origin and publication treatment
Modernized user supplied source
User-supplied origin; no independent authorship or license determination. Instructor code is not included.
New or rewritten source, limited sanitized historical excerpts when useful
No new license is asserted by this publication.