#include<iostream.h>
void prime(int n); //function declaration
int main()
{
int n; //variable declaration
cout<<"Please enter a valid 'n' value"<<endl;
cin>>n; //reading 'n' value
while(n<1) //validating 'n' value
{
cout<<"You have entered a invalid Number"<<endl;
cout<<"Please enter a valid Integer"<<endl;
cin>>n;
}
cout<<"serice of prime numbers upto 'n' is :"<<endl;
prime(n); //calling function
return 0; //successful termination
}
/* method 1...............*/
void prime(int n) //called function
{
int elem; //to check each element upto 'n' is whether prime or not
int fact; //to count the number of factors for each 'elem'
int i; //holds the factors of each 'elem' on run time
for(elem=2;elem<=n;++elem) //the possibility of prime number is >= '2'
{
fact=0; //to initialize the number of factors for each 'elem'
for(i=1;i<=elem;++i) //to check the factors of each 'elem'
{
if(elem%i==0) //factor divides the element without remainder
fact++; //counts the number of factors for each 'elem'
}
if(fact==2) //prime number has only '2' factors (1 and 'itself')
}
/* Method 2............*/
void prime(int n)
{
int elem,i;
bool flag=;
for(elem=2;elem<=n;++elem)
{
i=2;
flag=false;
while(!flag&&i<=elem/2)
{
if(elem%i==0)
flag=true;
++i;
}
if(flag==false)
cout<<"\n '"<<elem<<"' is a prime";
}
}
void prime(int n); //function declaration
int main()
{
int n; //variable declaration
cout<<"Please enter a valid 'n' value"<<endl;
cin>>n; //reading 'n' value
while(n<1) //validating 'n' value
{
cout<<"You have entered a invalid Number"<<endl;
cout<<"Please enter a valid Integer"<<endl;
cin>>n;
}
cout<<"serice of prime numbers upto 'n' is :"<<endl;
prime(n); //calling function
return 0; //successful termination
}
/* method 1...............*/
void prime(int n) //called function
{
int elem; //to check each element upto 'n' is whether prime or not
int fact; //to count the number of factors for each 'elem'
int i; //holds the factors of each 'elem' on run time
for(elem=2;elem<=n;++elem) //the possibility of prime number is >= '2'
{
fact=0; //to initialize the number of factors for each 'elem'
for(i=1;i<=elem;++i) //to check the factors of each 'elem'
{
if(elem%i==0) //factor divides the element without remainder
fact++; //counts the number of factors for each 'elem'
}
if(fact==2) //prime number has only '2' factors (1 and 'itself')
cout<<"\n '"<<elem<<"' is a prime"; //printing the prime number
}}
/* Method 2............*/
void prime(int n)
{
int elem,i;
bool flag=;
for(elem=2;elem<=n;++elem)
{
i=2;
flag=false;
while(!flag&&i<=elem/2)
{
if(elem%i==0)
flag=true;
++i;
}
if(flag==false)
cout<<"\n '"<<elem<<"' is a prime";
}
}
No comments:
Post a Comment