弥补您要编写一个函数 /方法来查找质数,这将是最有效的方法? 我认为这将是这样的测试:
SEMI-C ++中的代码下面
bool primeTest (int x) { //X is the number we're testing
int testUpTo = (int)((sqrt(x))+1);
for (int i=3; i<testUpTo; i+=2){
if ((x%i)==0) {
return false;
}
}
return true;
}
有人有更好的方法可以解决此问题,这将减少计算?
Edit:稍微更改代码,两次。 我没有想到任何特定的语言,尽管我认为由于bool这个词,我认为java上的c ++是java。
millerRabinTest,该测试很容易成为小于341,550,071,728,321的数字(和2^31远小得多)的确定性。 假码:有许多不同的情况。
x
(x & 1) != 0 || x == 2
x
x
x
小于4759123141(这就是其他所有内容):使用米勒·拉宾(Miller Rabin)的基地2、7和61.bool primeTest (int x){//X is the number we're testing
if (x == 1) return false;
if (x == 2 || x == 3) return true;
if(x%2 == 0 || x%3 == 0)
return false;
int testUpTo = (int)((sqrt(x))+1);
for(int i=6; i<=testUpTo; i+=6){
if ((x%(i-1))==0 || x%(i+1)==0){
return false;
}
}
return true;
}
的错误结果
wikipedia在此方面有一篇很好的文章:http://en.wikipedia.org/wiki/primality_test
您可以查看本文测试不同原始测试的性能:
Richard P. Brent的主要测试:Http://cs.anu.edu.au/student/comp4600/comletures/comp4600_primality.pdf