C++ Code To Check If A Number Is Prime

5 min read Jul 01, 2024
C++ Code To Check If A Number Is Prime

C++ Code to Check if a Number is Prime

This article will discuss how to write a C++ code to check if a given number is a prime number.

Understanding Prime Numbers

A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. In other words, a prime number has exactly two divisors: 1 and itself. For example, the first few prime numbers are 2, 3, 5, 7, 11, and 13.

C++ Code Implementation

#include 
#include 

using namespace std;

bool isPrime(int num) {
  // Handle special cases: 0, 1, and 2
  if (num <= 1) {
    return false;
  } else if (num <= 3) {
    return true;
  } else if (num % 2 == 0 || num % 3 == 0) {
    return false;
  }

  // Check for divisibility by 6k ± 1 up to the square root of num
  for (int i = 5; i * i <= num; i += 6) {
    if (num % i == 0 || num % (i + 2) == 0) {
      return false;
    }
  }

  // If no divisors found, it's a prime number
  return true;
}

int main() {
  int num;

  cout << "Enter a number: ";
  cin >> num;

  if (isPrime(num)) {
    cout << num << " is a prime number." << endl;
  } else {
    cout << num << " is not a prime number." << endl;
  }

  return 0;
}

Code Explanation:

  1. Header Files:

    • iostream: Provides input and output functionalities.
    • cmath: Provides mathematical functions like sqrt().
  2. isPrime(int num) Function:

    • Special Cases:
      • Numbers less than or equal to 1 are not prime.
      • 2 and 3 are prime numbers.
      • Even numbers greater than 2 are not prime.
      • Numbers divisible by 3 are not prime.
    • Optimized Check:
      • All prime numbers greater than 3 can be represented in the form 6k ± 1, where k is any integer.
      • The code iterates through numbers of the form 6k ± 1 up to the square root of the input number.
      • If the number is divisible by any of these numbers, it's not prime.
    • Return Value:
      • Returns true if the number is prime.
      • Returns false otherwise.
  3. main() Function:

    • Prompts the user to enter a number.
    • Calls the isPrime() function to check if the number is prime.
    • Prints the result to the console.

Running the Code:

  1. Save the code in a .cpp file (e.g., prime_checker.cpp).
  2. Compile the code using a C++ compiler (e.g., g++): g++ prime_checker.cpp -o prime_checker
  3. Run the compiled executable: ./prime_checker

The code will prompt you to enter a number, and it will output whether the number is prime or not.

Example Output:

Enter a number: 17
17 is a prime number.
Enter a number: 20
20 is not a prime number.

This code provides an efficient way to determine if a number is prime in C++. The optimized checking process reduces the number of iterations needed, making it faster for larger numbers.

Latest Posts