Thursday 9 June 2016

Check given number is prime

A prime number is a number divisible by only 1 and itself.

A number would never be divisible by numbers greater than half of itself.Suppose if you need to check whether 17 is a prime number then just check whether 17 is divisible by numbers<= 17/2.Numbers greater than 17/2 i.e greater than 8 would never divide 17 completely as they are greater than half of 17.


Code 

#include<stdio.h>

int main()
{
    int no,i=2;

    printf("Enter a no ");
    scanf("%d",&no);

    while(i<=no/2)
    {
        if(no % i)
        {
            i++;
            continue;
        }
        else
        {
            printf("\nNot a Prime no");
            break;
        }
    }
    if(i == no/2+1)
        printf("\nPrime no");

    return 0;
}


O/P


No comments:

Post a Comment