#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';
}
