我总是使用该代码来控制数字是否为素数:
#include <stdio.h>
int main() {
unsigned long long i, n;
int s;
printf("Enter the number: ");
scanf("%llu", &n);
if (n != 2) {
for (i = 2; i < n; i++) {
if (n%i == 0) {
s = 0;
break;
}
else {
s = 1;
}
}
}
else {
s = 1;
}
if (s == 1) {
printf("Prime.");
}
else {
printf("Not prime.");
}
return 0;
}
但是当我输入一个非常大的数字,如1365165888711511时,需要很长时间。 (我等了一个小时。(CPU:2.90GHz * 4,内存:8GB))
我的问题;有没有其他方法比上述算法更快地检查数字?
答案 0 :(得分:9)
这应该将执行时间缩短到几分钟而不是几小时,至少对于最佳数字而言:
for (i=3; i*i <= n; i += 2){
if (n % i == 0) {
s=0;
break;
}
无论O(sqrt n)
的素数是n
,都是O(n)
。对于素数n
,您的代码为i += 2
。由于Input: n > 3, an odd integer to be tested for primality;
Input: k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2^s·d with d odd by factoring powers of 2 from n − 1
WitnessLoop: repeat k times:
pick a random integer a in the range [2, n − 2]
x ← a*d mod n
if x = 1 or x = n − 1 then do next WitnessLoop
repeat s − 1 times:
x ← x^2 mod n
if x = 1 then return composite
if x = n − 1 then do next WitnessLoop
return composite
return probably prim
行,它的速度通常也是原来的两倍。
为了使速度更快,您需要进行概率测试,例如Miller-Rabin。:
if n < 2,047, it is enough to test a = 2;
if n < 1,373,653, it is enough to test a = 2 and 3;
if n < 9,080,191, it is enough to test a = 31 and 73;
if n < 25,326,001, it is enough to test a = 2, 3, and 5;
if n < 4,759,123,141, it is enough to test a = 2, 7, and 61;
if n < 1,122,004,669,633, it is enough to test a = 2, 13, 23, and 1662803;
if n < 2,152,302,898,747, it is enough to test a = 2, 3, 5, 7, and 11;
if n < 3,474,749,660,383, it is enough to test a = 2, 3, 5, 7, 11, and 13;
if n < 341,550,071,728,321, it is enough to test a = 2, 3, 5, 7, 11, 13, and 17.
请注意,对于许多值来说,这可能是确定性的:
当要测试的数量n很小时,尝试全部&lt; 2(ln n)^ 2不是必需的,因为已知足够多的潜在证人就足够了。例如,Pomerance,Selfridge和Wagstaff [8]以及Jaeschke [9]已经证实了
if n < 3,825,123,056,546,413,051, it is enough to test a = 2, 3, 5, 7, 11, 13, 17, 19, and 23.
if n < 2^64, it is enough to test a = 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, and 37.
利用Feitsma和Galway在2010年列举所有基2伪影的工作,这被扩展(参见OEIS A014233),后来第一个结果用江和邓的不同方法显示:[10]
if n < 318,665,857,834,031,151,167,461, it is enough to test a = 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, and 37.
if n < 3,317,044,064,679,887,385,961,981, it is enough to test a = 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, and 41.
Sorenson和Webster [11]验证了上述内容并计算了这些大于64位结果的精确结果:
$array
答案 1 :(得分:0)
加速算法的一种非常快捷的方法是,只能达到n的平方根并递增2,以避免尝试除偶数,如果2失败则总是失败。但是一些谷歌搜索会发现一些更复杂的算法,因为这是加密的一个非常关键的部分。有些事情可以帮助您进行搜索: &#34;幸运的是,在实践中有更复杂的算法来查找素数。这是Euler,Atkin和Sundaram的筛子。&#34; 摘自本网站:how to find primes 请注意,这不是我的链接。