Sunday 30 March 2014

How to find set of Prime Numbers by C programming.

How to find all the prime numbers within a given range in C Programming

Prime numbers are numbers which is divisible by 1 and by itself. This is a simple program which takes the range as input from user and find out all the possible prime numbers within the range.

#include"stdio.h" // Standard input output library
#include"conio.h" //console base input output library

// isPrime is a function returning 1 if n is a prime number otherwise return 0
int isPrime(int n)
{
if(n==1||n==2) // Check whether input is 1 or 2 if so exits returning 0
return 0;
for(int i=3;i<=n/2;i++) //start of for loop from 3 to half of the range number
{
if(n%i==0)  //   if n is divisible by i then number is not prime i.e. remainder returned is zero
return 0;
} // end of for loop
return 1;
}
void main()
{
int n;
clrscr();
printf("\nEnter number range : "); // Program asks for input  from user
scanf("%d",&n);  // input taken in integer variable
for(int i=1;i<=n;i++)
// iteration takes place from 1 to n i.e. the range, user gives only the upper  range
{
if(isPrime(i)) // check what function isPrime returns
printf("\n%d is a prime number",i); // if it returns 1 then print the number.
}
getch(); // Halt the console screen when finished until user press a key, this is not required in run time
}