且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

查找从2到1000的所有素数不起作用的算法

更新时间:2023-02-10 11:29:40

正如已经指出的那样, double s,只有大约16位精度,不够精确,不足以维持正确的余数,以便在足够高的数字上进行计算。

As has been pointed out, doubles, which only have about 16 digits of precision, aren't precise enough to maintain the correct remainders for calculations on high enough numbers.

你可以切换到 long 并执行你自己的模幂运算。

You can switch to longs and perform you own modular exponentiation.

int k = 1;
long sum = 0;
while(k<=n-1){
    long pow = 1;
    for (int i = 0; i < n - 1; i++)
        pow = (pow * k) % n;
    sum = (sum + pow)%n;
    k++;
}

这个算法可以通过将这种简单的模幂运算改为使用模幂运算来改进重复平方,它不是最有效的素数查找算法,但它现在是正确的。

This algorithm could be improved by changing this straightforward modular exponentiation to using modular exponentiation by repeated squaring, and it's not the most efficient prime finding algorithm, but it is now correct.

2 is a prime.
3 is a prime.
5 is a prime.
7 is a prime.
11 is a prime.
13 is a prime.
17 is a prime.
19 is a prime.
23 is a prime.
29 is a prime.
31 is a prime.

(剪辑)

977 is a prime.
983 is a prime.
991 is a prime.
997 is a prime.

要通过重复平方进行模幂运算,请替换

To make it modular exponentiation by repeated squaring, replace

long pow = 1;
for (int i = 0; i < n - 1; i++)
    pow = (pow * k) % n;

with

long pow = 1;
long square = k;
int exp = n - 1;
while (exp > 0)
{
    if ((exp & 1) == 1)
    {
        pow = (pow * square) % n;
    }
    square = (square * square) % n;
    exp >>= 1;
}

它连续测试指数的每个位,并将当前的平方乘以至 pow 如果已设置。

It tests each bit of the exponent in succession, and multiplies the current square in to pow if it's set.