# Prime number program in C

Prime number program in C: C program for prime number, this code prints prime numbers using C programming language. C program to check whether a number is prime or not. Prime number logic: a number is prime if it is divisible only by one and itself.

## Prime number program in C language

```#include<stdio.h>

int main()
{
int n, i = 3, count, c;

printf("Enter the number of prime numbers required\n");
scanf("%d",&n);

if ( n >= 1 )
{
printf("First %d prime numbers are :\n",n);
printf("2\n");
}

for ( count = 2 ; count <= n ;  )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf("%d\n", i);
count++;
}
i++;
}

return 0;
}```

Output of program:

Remember two is the only even and the smallest prime number. First few prime numbers are 2, 3, 5, 7, 11, 13, 17, .... Prime numbers have many applications in computer science and mathematics. A number greater than one can be factorized into prime numbers, for example, 540 = 22*33*51.

## C program for prime number or not

```#include<stdio.h>

main()
{
int n, c = 2;

printf("Enter a number to check if it is prime\n");
scanf("%d",&n);

for ( c = 2 ; c <= n - 1 ; c++ )
{
if ( n%c == 0 )
{
printf("%d is not prime.\n", n);
break;
}
}
if ( c == n )
printf("%d is prime.\n", n);

return 0;
}```

## C program for prime number using function

```#include<stdio.h>

int check_prime(int);

main()
{
int n, result;

printf("Enter an integer to check whether it is prime or not.\n");
scanf("%d",&n);

result = check_prime(n);

if ( result == 1 )
printf("%d is prime.\n", n);
else
printf("%d is not prime.\n", n);

return 0;
}

int check_prime(int a)
{
int c;

for ( c = 2 ; c <= a - 1 ; c++ )
{
if ( a%c == 0 )
return 0;
}
if ( c == a )
return 1;
}```

There are many efficient logics to check primality, one method given below is more efficient then the above method.

`for (c = 2; c <= (int)sqrt(n); c++)`

Only checking from 2 to square root of the number is sufficient. Even more efficient logics are available.