Ticker

6/recent/ticker-posts

Header Ads Widget

Responsive Advertisement

Prime Numbers in given Range

Problem Statement


In this program we will code a basic program to find prime numbers within a given range.

Code

#include 

void primeinrange(int m,int n)

{

int i,j;

int num=0;

int count=0;

for(i=m;i<=n;i++)

{

count=0;             

for(j=2;j<=i/2;j++)

{

if(i%j==0)

{

count=1;

}             

}

if(count==0)

{

printf("%d ",i);  

}             

}

}

int main()

{

int a,b;

printf("ENTER THE INNER RANGE : \n");

scanf("%d",&a);

printf("ENTER THE OUTER RANGE : \n");

scanf("%d",&b);

primeinrange(a,b);

return 0;

}

Output

ENTER THE INNER RANGE : 2

ENTER THE OUTER RANGE : 20

2 3 5 7 11 13 17 19  

Explanation 

In this problem we have to find all the prime numbers between inner and an outer range.


A prime number is a whole number greater than 1 whose only factors are 1 and itself. A factor is a whole numbers that can be divided evenly into another number. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29.

For checking a prime number,we run a for loop from i:2 to n/2, now if our number is divided by any value of 'i' we set our counter to 1 and exit. Once this loop ends and if counter=0 then our number is a prime number else not.

Post a Comment

0 Comments