Home

Awesome

correct_cpp_is_prime

BranchTravis CICodecov
masterBuild Statuscodecov.io

Correct C++ chapter 'is_prime'.

Goal

Prerequisites

Exercise

Write a command-line interface (CLI) program that determines if a number is a prime (see 'What is a prime?').

Here are the outputs and exit statuses the program should give:

Call to is_primeOutputExit status
./is_primeAny1
./is_prime X, where X is a number that is not primefalse (with newline)0
./is_prime Y, where Y is a number that is primetrue (with newline)0
./is_prime nonsenseAny1
./is_prime 7 42Any1

In this exercise, you start with the code below. Yes, that code works perfectly.

#include <cassert>
#include <string>
#include <iostream>

int main(int argc, char* argv[]) 
{
  if (argc != 2) return 1;
  try
  {
    const int value{std::stoi(argv[1])};
    // -1: unknown
    //  0: false
    //  1: true
    int is_prime = -1;

    //Trivial cases
    if (value < 2) is_prime = 0;
    if (is_prime == -1 && value == 2) is_prime = 1;

    //Complex cases
    for (int denominator=2; denominator!=value-1; ++denominator)
    {
      if (is_prime != -1) break;
      if (value % denominator == 0)
      {
        is_prime = 0;
      }
    }
    if (is_prime == -1) is_prime = 1;

    //Display the result
    assert(is_prime != -1); //Must be known now
    if (is_prime == 0)
    {
      std::cout << "false\n";
    }
    else
    {
      std::cout << "true\n";
    }
  }
  catch (const std::invalid_argument&)
  {
    return 1;
  }
  catch (const std::out_of_range&)
  {
    return 1;
  }
}

What is a prime?

Any number is a prime if it:

NumberIs prime?
-1No
0No
1No
2Yes
3Yes
4No
5Yes
6No
7Yes

External links