Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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?

like image 429
Waypoint Avatar asked Nov 29 '22 10:11

Waypoint


1 Answers

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)).

like image 165
vissi Avatar answered Dec 21 '22 02:12

vissi