http://acm.cs.ecnu.edu.cn/problem.php?problemid=1095
From:http://blog.sina.com.cn/s/blog_4d88e9860100b6dk.html
一开始看到这道题,想都没想就用了大数来做,为了防止超时,我还用了二分,刷的时候也是二分,但是还是TLE,后来同学提示我,可以用数字的位数来判断,于是时间又减少不少,但是还是超时,在判断数是否相等上还是时间太多,最后用概率算法终于可以实现。
#include <cstdio>
#include <deque>
#include <set>
#include <string>
#include <map>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
#define maxsize 500000
const int mod=7;
char str[maxsize];
int power(int a,int b)
{
int te = 1;
while(b){
if(b & 1)te = (te*a)%mod;
a = (a*a)%mod;
b >>= 1;
}
return te;
/*
if(b==1)return a;
int te=power((a*a)%mod,b/2);
if(b&1)return (a*te)%mod;
return te;
*/
}
int Mod(int len)
{
int x=0;
for(int i=0;i<len;i++)
{
x=x*10+str[i]-'0';
x%=mod;
}
return x;
}
int main()
{
int T;
cin>>T;getchar();
while(T--)
{
scanf("%s",str);getchar();
if(strcmp(str,"1")==0)
{
printf("1\n");
continue;
}
int len=strlen(str);
int i;
//for(i=1;i*log10((double)i)<=len;i++);i-=1;
int l = 1, r = 100001;
int ans;
while(l <= r){
int m = (l+r) >> 1;
if(m*log10((double)m)<=len){
ans = m;
l = m+1;
}
else r = m-1;
}
i = ans;
if(Mod(len)==power(i%mod,i))printf("%d\n",i);
else printf("-1\n");
}
return 0;
}