Using c program generate prime numbers between a range also calculate count of prime numbers




A number that is not divisible by any other numbers except that number and 1 is called a prime number.

this property is called primality. the largest prime number has 17,425,170 digits.

In this c program we need to generate prime numbers of a particular range and we need to find out the number of prime numbers displayed.

we are using a little complicated logic in this c program. first we check the given numbers are greater than 2. else program exits with message no prime. then we use a double for loop, in outer loop we checking numbers from M to N and set flag = 0.

Inside the inner for loop we check every number which is divisible by any number, if so we set the flag as 1. finally we display the numbers which flag is 0 as prime numbers.

we additionally uses a count variable to get the number of prime numbers between the range.

===================================================================
#include <stdio.h>
 
#include <conio.h>
 
#include <stdlib.h>
 
#include <math.h>
 
void main()
 
{
 
   int M, N, i, j, flag, temp, count = 0;  // declares the variables
 
   clrscr();
 
   printf("Enter the value of M and N\n");
 
   scanf("%d %d", &M,&N);
 
   if(N < 2)
 
   {
 
     printf("There are no primes upto %d\n", N);    /* check the numbers are greater than 2 */
 
     exit(0);
 
   }
 
   printf("Prime numbers are\n");
 
   temp = M;
 
   if ( M % 2 == 0)
 
   {
 
      M++;
 
   }
 
   for (i=M; i<=N; i=i+2)                     /* start of the outer loop and set the flag as zero */
 
   {
 
     flag = 0;
 
     for (j=2; j<=i/2; j++)                   /* inner loop to check the number is prime */
 
     {
 
	if( (i%j) == 0)
 
	{
 
	   flag = 1;
 
	   break;
 
	}
 
     }
 
     if(flag == 0)
 
     {
 
       printf("%d\n",i);                         /* print the number is prime if flag is zero */
 
       count++;
 
     }
 
   }
 
   printf("Number of primes between %d  and %d = %d\n",temp,N,count);
 
}
==================================================================
OUTPUT of C program to generate and print prime numbers
==================================================================
Enter the value of M and N
15 45
Prime numbers are
17
19
23
29
31
37
41
43
Number of primes between 15 and 45 = 8