Dec 1, 2016

Program: Print first n Prime Number

Program: Print first n Prime Number

We earlier done the program of how to check Prime Number, in that program we are checking whether the given number is prime or not.

In this program we are taking input n and printing first n prime number.


Prime number is a number which is greater than one and can only divide by 1 or by its own number.

#include <iostream>
using namespace std;

//we already discuss about how to check prime number so we create a function
bool isPrime(int n) 
{
       //this snippet is taken from program: Check given number for Prime Number
bool flag = true;
if(n<2)
flag = false;
else if(n == 2)
flag = true;

        else if(n%2 ==0)
              flag = false;
else{
for(int i=3;i<n;i+=2){
if(n%i == 0)
{
flag = false;
 break;
}
}

}
       return flag; //return boolean value
}

int main()
{
  int n,i;
  cout << "Enter value of n : ";
  cin >> n; //input n
  if(n>1)
  {
   cout << "2 ";
   n--;
  }
/*
we print first prime number i.e. 2 earlier to increase the speed of program as i discussed earlier in my last program that 2 is only even prime number. Rest of prime number are odd. So we have to print 2 earlier to run loop with increment of two. This way it checks less number of number and increase its speed.
Now loop run till n value drop to zero that each value we print will decrement value of n. So we can print exactly n number only. 
In loop we pick number and check whether it is prime or not from function which return true or false. According to result we print the prime number or not.
*/
  for(i=2;n>0;i+=2)
  {
      if(isPrime(i))
      {
          cout << i << " ";
          n--;
      }
  }
  return 0; // https://cplspls.blogspot.com
}



OUTPUT:

0 comments:

Post a Comment