1  #include <iostream>
  2  #include <cmath>
  3  using namespace std;
  4  
  5  int main()
  6  {
  7    cout << "Find all prime numbers <= n, enter n: ";
  8    int n;
  9    cin >> n;
 10  
 11    const int NUMBER_PER_LINE = 10; // Display 10 per line
 12    int count = 0; // Count the number of prime numbers
 13    int number = 2; // A number to be tested for primeness
 14  
 15    cout << "The prime numbers are:" << endl;
 16  
 17    // Repeatedly find prime numbers
 18    while (number <= n)
 19    {
 20      // Assume the number is prime
 21      bool isPrime = true; // Is the current number prime?
 22  
 23      // Test if number is prime
 24      for (int divisor = 2; divisor <= sqrt(number * 1.0); divisor++)
 25      {
 26        if (number % divisor == 0)
 27        { // If true, number is not prime
 28          isPrime = false; // Set isPrime to false
 29          break; // Exit the for loop
 30        }
 31      }
 32  
 33      // Print the prime number and increase the count
 34      if (isPrime)
 35      {
 36        count++; // Increase the count
 37  
 38        if (count % NUMBER_PER_LINE == 0)
 39        {
 40          // Print the number and advance to the new line
 41          cout << number << endl;
 42        }
 43        else
 44          cout << number << " ";
 45      }
 46  
 47      // Check whether the next number is prime
 48      number++;
 49    }
 50  
 51    cout << "\n" << count << " number of primes <= " << n << endl;
 52  
 53    return 0;
 54  }