//test whether it is prime number ot not
int prime_test(long int prime_number)
{
long int a, p;
srand((unsigned)time(NULL));
//0 and 1 not meaning for prime test.
a = rand() % (prime_number - 2) + 2;
printf("a -> %li\n", a);
//Lehmann Algorithm, p = a^((prime_number-1)/2) mod prime_number
p = (long int)pow(a, (prime_number - 1) / 2) % prime_number;
printf("p -> %li\n", p);
if(p != 1 & (prime_number - p) != 1)
{
printf("Enter number is not prime number.\n");
return 0;
}
else
{
printf("Enter number is prime number.\n");
return 1;
}
}
我的问题是为什么我得到负面的p -984,实际上1997是素数,
它也应该是1或-1。
输出如下:
输入素数p:1997
a - > 1557
p - > -984
输入的数字不是素数!
temp1 - > 0
请重新输入素数p:
答案 0 :(得分:4)
1557 ^ 998不太适合long int
。
更有建设性:如果你这样计算p
,则需要更长的时间,但要避免溢出:
p = 1;
for ( i=0; i<(prime_number-1)/2; i++ )
p = (p*a) % prime_number;
有非常好的方法来优化它,但我会将其作为练习。