同余
思路
x
x
x个
8
8
8连在一起组成的正整数连在一起可写作
8
∗
(
1
0
x
−
1
)
9
\dfrac{8 * (10^x-1)}{9}
98∗(10x−1)。那么题目就转化为让我们求出一个最小的
x
x
x满足
L
∣
8
∗
(
1
0
x
−
1
)
9
L|\dfrac{8 * (10^x-1)}{9}
L∣98∗(10x−1)。设
d
=
g
c
d
(
L
,
8
)
d=gcd(L,8)
d=gcd(L,8)。
L
∣
8
∗
(
1
0
x
−
1
)
9
⟺
9
∗
L
∣
8
∗
(
1
0
x
−
1
)
⟺
9
∗
L
d
∣
1
0
x
−
1
⟺
1
0
x
≡
1
(
m
o
d
9
∗
L
d
)
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})
L∣98∗(10x−1)⟺9∗L∣8∗(10x−1)⟺d9∗L∣10x−1⟺10x≡1(modd9∗L)
引
理
:
引理:
引理:
若正整数
a
,
n
a,n
a,n互质,则满足
a
x
≡
1
(
m
o
d
n
)
a^x \equiv 1(mod \quad n)
ax≡1(modn)的最小正整数
x
0
x_0
x0是
ϕ
(
n
)
\phi(n)
ϕ(n)的约数。
设
ϕ
(
n
)
=
q
x
0
+
r
,
(
0
<
r
<
x
0
)
\phi(n)=qx_0+r,(0< r < x_0)
ϕ(n)=qx0+r,(0<r<x0)。因为
a
x
0
≡
1
(
m
o
d
n
)
a^{x_0} \equiv 1(mod \quad n)
ax0≡1(modn),所以
a
q
x
0
≡
1
(
m
o
d
n
)
a^{qx_0} \equiv 1(mod \quad n)
aqx0≡1(modn)。根据欧拉定理有
a
ϕ
(
n
)
≡
1
(
m
o
d
n
)
a^{\phi(n)} \equiv 1(mod \quad n)
aϕ(n)≡1(modn),所以
a
q
x
0
∗
a
r
≡
1
(
m
o
d
n
)
a^{qx_0} * a^{r} \equiv 1(mod \quad n)
aqx0∗ar≡1(modn),即
a
r
≡
1
(
m
o
d
n
)
a^{r} \equiv 1(mod \quad n)
ar≡1(modn)。这与
x
0
x_0
x0最小矛盾。故假设不成立,原命题成立。
证
毕
。
证毕。
证毕。
根据以上引理,我们只需求出欧拉函数
ϕ
(
9
∗
L
d
)
\phi(\dfrac{9 * L}{d})
ϕ(d9∗L),枚举它的所有约数,用快速幂注意检查是否满足条件即可。时间复杂度为
O
(
L
l
o
g
L
)
O(\sqrt{L}logL)
O(LlogL)。
**注意:**这道题题目数据太大,就算用快速幂取模,开了
l
o
n
g
l
o
n
g
long long
longlong也会
b
o
o
m
boom
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;
}