Pollard-Rho被卡飞求改
查看原帖
Pollard-Rho被卡飞求改
408071
TankYu楼主2024/6/20 19:29

RT,以下的PR在无任何其他操作时用时2.5s,求可以优化常数的地方

int p[20] = {0, 2, 3, 5, 7, 11};

LL ksm(LL a, LL b, LL mod)
{
    LL ans = 1;
    while (b)
    {
        if (b & 1)
        {
            ans *= a;
            ans %= mod;
        }
        a *= a;
        a %= mod;
        b >>= 1;
    }
    return ans;
}

bool mr(int n, int x)
{
    int b = n - 1;
    while (b % 2 == 0)
    {
        b /= 2;
    }
    x = ksm(x, b, n);
    while (b < n - 1 && x != 1 && x != n - 1)
    {
        x *= x;
        x %= n;
        b <<= 1;
    }
    return x == n - 1 || b % 2 == 1;
}

bool check(int x)
{
    if (x == 1)
    {
        return 0;
    }
    for (int i = 1; i <= 5; i++)
    {
        if (x == p[i])
        {
            return true;
        }
        if (x % p[i] == 0)
        {
            return false;
        }
        if (!mr(x, p[i]))
        {
            return false;
        }
    }
    return true;
}

LL f(LL x, LL c, LL n)
{
    return (x * x % n + c) % n;
}
mt19937 gen(chrono::system_clock::now().time_since_epoch().count());

LL pr(LL n)
{
    if (n == 4)
    {
        return 2;
    }
    uniform_int_distribution<LL> rand(3, n - 1);
    LL x = rand(gen);
    LL y = x, c = rand(gen);
    x = f(x, c, n);
    y = f(f(y, c, n), c, n);
    for (int i = 0; x != y; i = min(i << 1, 64ll))
    {
        LL cnt = 1;
        for (int j = 0; j < i; j++)
        {
            cnt *= abs(x - y) % n;
            cnt %= n;
            if (cnt == 0)
            {
                break;
            }
            x = f(x, c, n);
            y = f(f(y, c, n), c, n);
        }
        LL tmp = __gcd(cnt, n);
        if (tmp != 1)
        {
            return tmp;
        }
    }
    return n;
}
2024/6/20 19:29
加载中...