【数学问题】判断一个数是否是素数

若n为素数,则其不能被2,3,...,n-1 整除。

更加快速的判定方法:

判断n能否被2,3,...,⌊√n ⌋ 整除。

1、代码:

#include<iostream>
#include<cmath>
using namespace std;

bool isPrime(int n)
{
	if(n<=1) return false;
	
	int sqr=(int)sqrt(1.0*n);
	
	for(int i=2;i<=sqr;i++)
	{
		if(n%i==0) return false;
	}
	return true;
}


int main(){
	int n;	
	
	while(cin>>n)
	{
		cout<<isPrime(n)<<endl;
	} 
	
	return 0;	
}

2、结果:

 

猜你喜欢

转载自blog.csdn.net/OpenStack_/article/details/88728993