Waypoint Waypoint - 2 months ago 6
C Question

C - how to test easily if it is prime-number?


Possible Duplicates:

C - determine if a number is prime




Is there any way to test easily in C whether a selected number is prime or not?

Answer

The easiest way is writing a loop, like:

int is_prime(int num)
{
     if (num <= 1) return 0;
     if (num % 2 == 0 && num > 2) return 0;
     for(int i = 3; i < num / 2; i+= 2)
     {
         if (num % i == 0)
             return 0;
     }
     return 1;
}

You can then optimize it, iterating to floor(sqrt(num)).

Comments