All solutions in C++ editorial are incorrect


#1

In editorial all solutions do the same mistake:
for (int i = 2; i <= sqrt(A); ++i) {
if (A % i == 0) return 0;
}

This already fails if A is 2, which is a prime number, but we will return 0.
Also, there is no need to calculate a costly square root. You can use i*i <= A instead.
Here is my full solution:

int Solution::isPrime(int A) {
if (A < 2) return 0;
if (A == 2) return 1;

for (int i = 2; i*i <= A; ++i) {
    if (A % i == 0) return 0;
}
return 1;

}


#2

Right. Thanks man :slight_smile:


#3

The solution is correct. The for loop won’t be executed at all for A=2 because i*i is 4 which is NOT less than A. So the function won’t return 0. It will return 1.