#### C Program to Find Prime Number:

#include <stdio.h> int main() { int num, i, is_prime; printf("Enter a number: "); scanf("%d",&num); is_prime = 0; if(num<2) is_prime = 0; else if(num == 2) is_prime = 1; else { for(i=2;i <= num/2;i++) { if(num%i==0) { is_prime = 0; break; } else is_prime = 1; } } if(is_prime == 0) printf("The number is not Prime!"); else printf("The number is Prime!"); return 0; }

The above algorithm is little bit slower. So make this line:

for(i=2;i <= num/2;i++)

to

for(i=2;i <= (int)sqrt(num);i++)

and include the header file math.h.

Thanks. I was looking for this.

ReplyDelete