C++ isPrime finction

Hello everyone,
Can someone pls explain this code to me.

#include
using namespace std;

// function to check prime number
int check_prime(int n) {

// 0 and 1 are not prime numbers
if (n == 0 || n == 1) {
return 0;
}

for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0)
return 0;
}

return 1;
}

int main() {

bool result = check_prime(67);

if (result == 1)
cout << “Prime Number”;
else
cout << “Non-prime Number”;

return 0;
}

// Output: Prime Number

Have you run the compiled code?

Sorry, for the typo in title. I wrote this while about to sleep.
I copied this code from a phone app I use to practice C++. My only question here is with the number (2). I know that it is a prime number but the function will test 2%2 and gets 0, so it should output (not prime), which is wrong, but it is working perfectly and it outputs that 2 is prime. Can someone please just explain this part to me? Thank you

When n/2 is 2, n is 4. When n is 2, it falls through the loop and goes directly to return 1.

oh I see. thank you very much. i was confused thinking n would be 2 and 2%2 == 0.

1 Like

Technically speaking, we are exploring a domain that is,

  • Real
  • Integer
  • Natural

Emphasis on the last one. Prime numbers are found only within the Natural number set. At least there are some constraints.

Any value less than plus two is not worth evaluating since it is moot.

if n < 2: raise ValueError

That’s pseudo code so don’t try to run it unless it’s in Python.

The technique used in the above code (OP) is known as ‘brute force’. It chews through all the values from a to b and checks for divisibility. Failing that yields a prime.

If one is looking for criticism of this algorithm, none is forthcoming. It is what it is and we know how it works. That is enough critical discussion.

In any language we are going to want to keep any iterative process in tight check, and demand very little of such processes. Primeness is a great CS101 subject to explore at length, or reasonably great depth, even as a breather from one’s course load. Tease your brain.