CppIsPrime.md

January 6, 2018 ยท View on GitHub

(C++) IsPrime

IsPrime is a Check code snippet to determine if an int is prime.

#include <cmath>

bool IsPrime(const int x) noexcept
{
  const int max{
    static_cast<int>(
      std::sqrt(static_cast<double>(x))
    ) + 1
  };

  for (int i=2; i!=max; ++i)
  {
    if (x % i == 0) return false;
  }

  return true;
}

External links

  • Correct C++ 'is_prime' chapter