同余 —— AcWing 202.最幸运的数字

image

同余

思路

  \(x\)\(8\)连在一起组成的正整数连在一起可写作\(\dfrac{8 * (10^x-1)}{9}\)。那么题目就转化为让我们求出一个最小的\(x\)满足\(L|\dfrac{8 * (10^x-1)}{9}\)。设\(d=gcd(L,8)\)
    \(L|\dfrac{8 * (10^x-1)}{9} \Longleftrightarrow 9*L|8*(10^x-1) \Longleftrightarrow \dfrac{9*L}{d}|10^x-1 \Longleftrightarrow 10^x \equiv 1(mod\dfrac{9*L}{d})\)
\(引理:\)
  若正整数\(a,n\)互质,则满足\(a^x \equiv 1(mod \quad n)\)的最小正整数\(x_0\)\(\phi(n)\)的约数。
  设\(\phi(n)=qx_0+r,(0< r < x_0)\)。因为\(a^{x_0} \equiv 1(mod \quad n)\),所以\(a^{qx_0} \equiv 1(mod \quad n)\)。根据欧拉定理有\(a^{\phi(n)} \equiv 1(mod \quad n)\),所以\(a^{qx_0} * a^{r} \equiv 1(mod \quad n)\),即\(a^{r} \equiv 1(mod \quad n)\)。这与\(x_0\)最小矛盾。故假设不成立,原命题成立。
\(证毕。\)
  根据以上引理,我们只需求出欧拉函数\(\phi(\dfrac{9 * L}{d})\),枚举它的所有约数,用快速幂注意检查是否满足条件即可。时间复杂度为\(O(\sqrt{L}logL)\)
注意:这道题题目数据太大,就算用快速幂取模,开了\(long long\)也会\(boom\)的一下炸掉,送给你一个奇怪的数字,所以需要用到龟速乘。

代码

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;

typedef long long LL;

LL n;

LL gcd(LL a, LL b) 
{
    return b ? gcd(b, a % b) : a;
}

LL get_phi(LL n) 
{
    LL res = n;
    for (LL i = 2; i <= n / i; i ++ ) 
        if (n % i == 0) 
        {
            res = res / i * (i - 1);
            while (n % i == 0) n /= i;
        }

    if (n > 1) res = res / n * (n - 1);
    return res;
}

LL qmul(LL a, LL k, LL mod) 
{
    LL res = 0, t = a % mod;
    while (k) 
    {
        if (k & 1) res = (res + t) % mod;
        k >>= 1;
        t = (t + t) % mod;
    }

    return res;
}

LL qpow(LL a, LL k, LL mod) 
{
    LL res = 1 % mod, t = a % mod;
    while (k) 
    {
        if (k & 1) res = qmul(res, t, mod) % mod;
        k >>= 1;
        t = qmul(t, t, mod) % mod;
    }
    res = res % mod;

    return res;
}

int main() 
{
    for (int T = 1; cin >> n, n; T ++ )
    {
        LL c = n / gcd(8, n) * 9;
        LL phi = get_phi(c);

        LL res = 1e18;
        for (LL i = 1; i <= phi / i; i ++ ) 
            if (phi % i == 0)
            {
                if (qpow(10, i, c) == 1) res = min(res, i);
                if (qpow(10, phi / i, c) == 1) res = min(res, phi / i);
            }

        printf("Case %d: ", T);
        printf("%lld\n", res == 1e18 ? 0 : res);
    }

    return 0;
}
posted @ 2021-05-20 21:03  筱翼深凉  阅读(89)  评论(0编辑  收藏  举报