C Program To Find Prime Number

A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not a prime number is called a composite number. For example, 5 is prime because only 1 and 5 evenly divide it, whereas 6 is composite because it has the divisors 2 and 3 in addition to 1 and 6. [Definition from Wikipedia]

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.

1 comments :

Spam comments will be deleted. :)

 
Loading...
TOP