fast way to check if a number is prime C++

Check if a Number is Prime in C++

To check if a number is prime in C++, follow these steps:

Step 1: Start with the Number and Check for Base Cases

bool isPrime(int n) {
    if (n <= 1) {
        return false;
    }
    if (n <= 3) {
        return true;
    }
    if (n % 2 == 0 || n % 3 == 0) {
        return false;
    }
    // Starting from 5, check for prime
}

Step 2: Loop to Check for Prime

for (int i = 5; i * i <= n; i = i + 6) {
    if (n % i == 0 || n % (i + 2) == 0) {
        return false;
    }
}
return true;

In this method, we check if the number is less than or equal to 1 and handle the base cases. Then, we start a loop from 5 and check if the number is divisible by i or i+2. If it is, we return false; otherwise, the number is prime and we return true.