# 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. 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.

## Prime number program in C language

1. #include<stdio.h>
2.
3. int main()
4. {
5.    int n, i = 3, count, c;
6.
7.    printf("Enter the number of prime numbers required\n");
8.    scanf("%d",&n);
9.
10.    if ( n >= 1 )
11.    {
12.       printf("First %d prime numbers are :\n",n);
13.       printf("2\n");
14.    }
15.
16.    for ( count = 2 ; count <= n ;  )
17.    {
18.       for ( c = 2 ; c <= i - 1 ; c++ )
19.       {
20.          if ( i%c == 0 )
21.             break;
22.       }
23.       if ( c == i )
24.       {
25.          printf("%d\n", i);
26.          count++;
27.       }
28.       i++;
29.    }
30.
31.    return 0;
32. }

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

1. #include<stdio.h>
2.
3. main()
4. {
5.    int n, c = 2;
6.
7.    printf("Enter a number to check if it is prime\n");
8.    scanf("%d",&n);
9.
10.    for ( c = 2 ; c <= n - 1 ; c++ )
11.    {
12.       if ( n%c == 0 )
13.       {
14.          printf("%d isn't prime.\n", n);
15.      break;
16.       }
17.    }
18.    if ( c == n )
19.       printf("%d is prime.\n", n);
20.
21.    return 0;
22. }

## C program for prime number using function

1. #include<stdio.h>
2.
3. int check_prime(int);
4.
5. main()
6. {
7.    int n, result;
8.
9.    printf("Enter an integer to check whether it is prime or not.\n");
10.    scanf("%d",&n);
11.
12.    result = check_prime(n);
13.
14.    if ( result == 1 )
15.       printf("%d is prime.\n", n);
16.    else
17.       printf("%d isn't prime.\n", n);
18.
19.    return 0;
20. }
21.
22. int check_prime(int a)
23. {
24.    int c;
25.
26.    for ( c = 2 ; c <= a - 1 ; c++ )
27.    {
28.       if ( a%c == 0 )
29.      return 0;
30.    }
31.    if ( c == a )
32.       return 1;
33. }

There are many efficient logics than this to check primality, one method given below.

`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.