Solved

# Problem with c# code that checkes if a number is prime

Posted on 2014-10-18

This is my method that checks if a parameter named "num" is prime.

private bool isPrime(int num)

{

if (num == 0 || num == 1)

return false;

for (int j = 2; j < num; j++)

if (num % j == 0) return false;

return true;

}

It works 100% of the time. However, my instructor wants us to use Math.Sqrt() in the code. So I changed the for loop to this.

for (int j = 2; j < Math.Sqrt(num); j++)

The change slightly decreased its effectiveness-- now it works 99.8% of the time. It's not 100% because every once in a while it calculates a number to be prime when in fact it is not prime. For example, for numbers 1 to 10000, the numbers that the method incorrectly identifies as prime are shown below.

4

9

49

121

289

361

529

841

961

1369

1681

2209

2809

3599

3721

5041

5183

5329

6241

6889

9409

Does anyone know how to correct this minor glitch?