题解
参考这篇题解 - poj3696 快速幂的优化+欧拉函数+gcd的优化+互质
由8构成的数可以写成 1 0 n − 1 9 ∗ 8 \cfrac{10^n-1}{9}*8 910n−1∗8,
所以题目可以改成求
首先,要知道一个性质:
当 a x = b y ax=by ax=by 且 ( a , b ) (a,b) (a,b) 互质时,说明a的因子里没有b,那么要使等式成立,b一定在x中,即x可以乘除b
然后设
d
=
g
c
d
(
8
,
L
)
d=gcd(8,L)
d=gcd(8,L) 我觉得gcd(8,9L)没准也可以,则有:
此时,
8
d
\cfrac{8}{d}
d8 与
L
d
\cfrac{L}{d}
dL 互质,且8里面没有9的因子,所以
8
d
\cfrac{8}{d}
d8 与
9
L
d
\cfrac{9L}{d}
d9L 也是互质
因此可以得出 1 0 n − 1 10^n-1 10n−1 一定是 9 L d \cfrac{9L}{d} d9L 的倍数
即,
现在有没有觉得这个公式是不是有点像欧拉定理:
欧拉定理告诉我们
a
φ
(
m
)
a^{\varphi(m)}
aφ(m) 一定是一个满足条件的解,把公式带入一下就变成
φ
(
9
L
d
)
\varphi(\cfrac{9L}{d})
φ(d9L) 是一个满足条件的解,但是不一定是题目要求的最小的解,
已知当n=0时,是一个满足条件的解,所以最小的解还可能存在 0~ φ ( 9 L d ) \varphi(\cfrac{9L}{d}) φ(d9L) 之间,
并且,因为有模数,而余数有是有循环节的,所以一定存在一个循环r,使得 a r = a m + r = 1 ( m o d m ) a^r=a^{m+r}=1(mod\,m) ar=am+r=1(modm),
因此,这个最小解一定是 φ ( 9 L d ) \varphi(\cfrac{9L}{d}) φ(d9L) 的因子,
那么,遍历一遍 φ ( 9 L d ) \varphi(\cfrac{9L}{d}) φ(d9L) 的因子就可以了
一些注意事项:
- 由于 L L L可能很大,在快速幂的过程中可能会爆范围(一定的),因此必须采用快速幂+快速乘
- 拆因子的过程中,o(n)的方法会T,一定要 n \sqrt{n} n
- 本代码能过acwing,但是poj上没试过
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll L, mod;
ll phi(ll n) {
ll res = n;
for (ll i = 2; i * i <= n; ++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 multi(ll a, ll b) {
ll res = 0;
while (b) {
if (b & 1) res = (res + a) % mod;
a = (a * 2) % mod;//*2
b >>= 1;
}
return res;
}
ll qpow(ll a, ll b) {
ll res = 1;
while (b) {
if (b & 1)res = multi(res, a);
b >>= 1;
a = multi(a, a);
}
return res;
}
int main() {
ios::sync_with_stdio(0);
int cs = 0;
while (cin >> L && L) {
printf("Case %d: ", ++cs);
ll d = __gcd(8ll, L);
mod = L / d * 9;
ll n = phi(mod);
ll ans = 1e18, a;
for (ll i = 1; i * i <= n; ++i) {
if (n % i == 0) {
a = qpow(10, i);
if (a == 1) {
ans = i;
break;
}
a = qpow(10, n / i);
if (a == 1) ans = min(ans, n / i);
}
}
if (ans == 1e18) puts("0");
else printf("%lld\n", ans);
}
return 0;
}