求n是不是素数。

输入一个数n,判断n是不是素数。

#include<iostream>
using namespace std;
int main()
{
	int  n;          //判断n是不是素数,n>0。 
	cin>>n;
	cout<<endl;
	int i=2;          
	int k;
	if(n==1)
	k=0;
	else if(n==2)
	k=1;
	else
	{
		while(i<n)     //可以用for(i=2;i<n;i++)
			if(n%i==0)
			{
			k=0;
			break;	
			}
		if(i==n)
		k=1;
	
		
	}
	
	if(k==1)
	cout<<n<<" is Prime number"<<endl;
	  else
	  cout<<n<<" is not Prime number"<<endl;
	return 0;
}
/*输出1~m之间所有的素数
如果m=1;输出此区间无素数
*/


#include<iostream>
#include <iomanip>
using namespace std;
int main()
{
	int  m;          //输出1到m之间所有的质素 
	cin>>m;
	cout<<endl;    
	int i=2,n;        
	int k;
	if(m==1)         //m=1;输入区间无素数。 
	cout<<"此区间无质素 ";
	else if(m==2)
	cout<<m<<" ";
	else
	{    cout<<setw(10)<<"2";
	     k=1; 
	     for(n=3;n<=m;n++)
	     {
		    for(i=2;i<n;i++)
			     if(n%i==0)
				 break;	
			if(i==n)
				{
				if(k%5==0)
				cout<<endl;	
				cout<<setw(10)<<n;
				k++;	
				} 	
		 }	 
	}		 
return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42387291/article/details/82805824