Wednesday 3 September 2014

C Program to check a number is prime or composite

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 1 and 5 are its only positive integer factors, whereas 6 is composite because it has the divisors 2 and 3 in addition to 1 and 6.

Examples of prime numbers are:  2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,.....

Let us see a function to check whether a number is prime or not.

// Function to check prime returns 0 or 1
int isprime(int value) {
    int i;
    for (i=2;i<=value/2;i++)
        if (value%i==0)
            return (0);
    return 1;
}

Here value is the number to be checked given as parameter to the function. This function returns 1 if the value prime and returns 0 if it is not.

No comments:

Post a Comment