Program to calculate prime numbers in a given range

A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not a prime number is called a composite number.
for example-5 is a prime number as it is divisible only by 5 and 1. 
#include<bits/stdc++.h>
#define max 1000000
//array for storing prime numbers

int a[max];
int main()

{
int i=0;j=0;p=0;q=0;k=0,flag;
//Enter any range

printf("enter the range:");

scanf("%d %d",&p,&q);

//loop for the whole range
for(j=p;j<=q;j++)
{

flag=0;

//if number is not even then enter to next level
if(j%2!=0 || j==2)
{

//check the number if it is a prime or not

for(i=3;i<=sqrt(j);i+=2)
{
if(j%i==0)
{

flag=1;
break;

}
}

//if flag=0 means j is prime so store this into array
if(flag==0)
a[k]=j;
k++;
}

}

//print the array

cout<<"primes numbers are-\n";
for(i=0;i<k;i++)
cout<<a[i];
return 0;}

OUTPUT-
Enter the range:0 10
prime numbers are-
2 3 5 7



Comments :

Post a Comment