题目传送门:http://poj.org/problem?id=3696
题目大意:给出一个数 L L ,请求出一个最小的数ans,使得ans全由8组成(即ans=88888……8),并且是的倍数。要求输出ans的位数。多组数据。 1≤L≤2∗109 1 ≤ L ≤ 2 ∗ 10 9 。
题目分析:一道很神的题,要是思路错了就走远了。
我一开始的想法是把8提出来,然后化成11111……1的形式,结果什么都推不出来QAQ。后来膜了题解,发现自己果真走远了。题解是乘以一个 98 9 8 ,变成99999……9的形式。这样的好处是99999……9(k个9)等于 10k−1 10 k − 1 。然后就可以一本正经地推式子:
接下来我们求出 L L 中质因子2的个数,很明显这个个数多于3便无解。若小于等于3,将其与8约去。在此不妨假设中有两个2。令 l=9L4 l = 9 L 4 ,则式子变为:
右边的2应该由 x x 贡献得来,所以便有:
现在我们要求最小的合法的k。
若 l l 是5的倍数,则这个式子无解。否则根据欧拉定理,若与 p p 互质,则有。换句话说,由于10与 l l 互质,所以以 ϕ(l) ϕ ( l ) 为循环。而且由于 10ϕ(l)≡1(modl) 10 ϕ ( l ) ≡ 1 ( mod l ) ,我们只要枚举 ϕ(l) ϕ ( l ) 的因数 e e ,查看是否符合要求即可(即是否有一个更小的循环)。注意快速幂的时候直接相乘会爆long long,要用快速乘。时间复杂度 O(TL−−√log2(L)) O ( T L log 2 ( L ) ) 。
CODE:
#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<stdio.h>
#include<algorithm>
using namespace std;
typedef long long LL;
LL n;
LL Phi()
{
LL sn=(long long)floor( sqrt( (double)n )+1e-4 );
LL temp=n,N=n;
for (LL i=2; i<=sn; i++) if (N%i==0)
{
while (N%i==0) N/=i;
temp=temp/i*(i-1LL);
}
if (N>1) temp=temp/N*(N-1);
return temp;
}
LL Mul(LL x,LL y)
{
if (!y) return 0;
LL temp=Mul(x,y>>1);
temp=(temp+temp)%n;
if (y&1) temp=(temp+x)%n;
return temp;
}
LL Pow(LL x,LL y)
{
if (!y) return 1LL;
LL temp=Pow(x,y>>1);
temp=Mul(temp,temp);
if (y&1) temp=Mul(temp,x);
return temp;
}
int main()
{
freopen("3696.in","r",stdin);
freopen("3696.out","w",stdout);
int t=0;
scanf("%I64d",&n);
while (n)
{
t++;
int num=0;
while (!(n&1)) n>>=1,num++;
if ( num>3 || n%5==0 ) printf("Case %d: 0\n",t);
else
{
n*=9;
LL m=Phi();
LL sm=(long long)floor( sqrt( (double)m )+1e-4 );
LL ans=m;
for (LL i=1; i<=sm; i++) if (m%i==0)
{
if (Pow(10,i)==1) ans=min(ans,i);
if (Pow(10,m/i)==1) ans=min(ans,m/i);
}
printf("Case %d: %I64d\n",t,ans);
}
scanf("%I64d",&n);
}
return 0;
}