C++ Program to generate 100 Prime Nos.

#include<iostream>
#include<cmath>
using namespace std;
int prime(int n);	//function for checking if the no. is prime or not
int prime(int n)	
{
	int i,flag=0;				//i for loop(dividing the no. with 1 to sqrt of the no. and a variable called flag 
	for (i=1;i<=sqrt(n);i++)	//a no. is prime if it is divisible by only 1 when divided by nos. upto the root of the no.
	{								
		if (n%i==0)				//if the no. is divisible by i
		{						
			flag+=1;			//increment flag
		}
	}
	if (flag==1)				//if flag=1 i.e theno. is divisible by only 1 when divided by nos. upto the root of the no.
	return 1;					//return 1;
	else 
	return 0;
}
int main()
{
	int n=2,j,count=1;			//n i.e the no. to be checked if it is prime or not(we start it by 2 as 1 is nota prime no.) and count keeps track of the no. of prime nos. detected
	cout<<"The first hundred prime nos. are"<<endl;
	while (count<101)
	{
		j=prime(n);				//checkif n is prime
		if (j==1)				//if it is prime, display n and increment count
		{
			count++;
			cout<<n<<endl;;
		}
		else 					//else dont increment count
		count=count;	
		n++;					//increment n(so that the next no. can be checked and so on
	}
	return 0;
}

[wpedon id="7041" align="center"]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.