#include <iostream> #include <math.h> #include <stdlib.h> bool isPrime(unsigned long n){ if(n == 2 || n == 3) return true; if(n%6 != 1 && n%6 != 5)//素数聚集原理 return false; float nsqrt = floor(sqrt((float)n)); //若小于nsqrt的数中不存在因数则大于nsqrt的数中也不会存在其因数。 //n = 6*x + 1 or 6*x -1,它非2、3和6的倍数。 for(int i = 6; i <= nsqrt; i += 6){ if(n%(i-1) == 0 || n%(i+1) == 0) return false; } return true; } int main(){ char buf[256]; int n = 0; while(std::cin>>buf){ n = atoi(buf); std::cout<<n<<" "<<(isPrime(n) ? "is Prime" : "not Prime")<<std::endl; } }参考资料:http://blog.csdn.net/huang_miao_xin/article/details/51331710
快速判断一个数是否是素数
猜你喜欢
转载自blog.csdn.net/jshnaoko/article/details/79642635
今日推荐
周排行