###### UVA - 11549 Calculator Conundrum (循环节)(Floyd判圈算法,快慢指针)

Alice got a hold of an old calculator that can display
n
digits. She was bored enough to come up with
the following time waster.
She enters a number
k
then repeatedly squares it until the result over ows. When the result
over ows, only the
n
most signi cant digits are displayed on the screen and an error ag appears. Alice
can clear the error and continue squaring the displayed number. She got bored by this soon enough,
but wondered:
\Given
n
and
k
, what is the largest number I can get by wasting time in this manner?”
Input
The rst line of the input contains an integer
t
(1

t

200), the number of test cases. Each test case
contains two integers
n
(1

n

9) and
k
(0

k<
10
n
) where
n
is the number of digits this calculator
can display
k
is the starting number.
Output
For each test case, print the maximum number that Alice can get by repeatedly squaring the starting
number as described.
SampleInput
2
1 6
2 99
SampleOutput
9
99

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
#include<set>
#include<cmath>

set<int> S;

int main(){
int T,n,k;
scanf("%d",&T);
while(T--){
scanf("%d%d",&k,&n);
int ans=n;
S.clear();
int now=n;
long long t;
while(true){
t=(long long)now*now;
int sum=0;
int digit=(int)log10(t)+1;
if(digit>k){
for(int i=0;i<digit-k;++i){
t/=10;
}
}
if(S.find((int)t)!=S.end())break;
ans=max(ans,(int)t);
S.insert(t);
now=t;
}
printf("%d\n",ans);
}
return 0;
}


#include<cstdio>
#include<cmath>
#include<iostream>
using namespace std;

int Next(int now,int k){
long long t=(long long)now*now;
int digit=(int)log10(t*1.00)+1;
if(digit>k){
for(int i=0;i<digit-k;++i)t/=10;
}
return (int)t;
}

int main() {
int T,n,k;
scanf("%d",&T);
while(T--) {
scanf("%d%d",&n,&k);
int ans=k;
int slow=k,fast=Next(k,n);
while(slow^fast) {
slow=Next(slow,n);
if(fast>ans)ans=fast;
fast=Next(fast,n);
if(fast>ans)ans=fast;
fast=Next(fast,n);
}
printf("%d\n",ans);
}
return 0;
}


#### Floyd判圈算法理解

2015-11-24 18:16:24

#### 关于Floyd判圈算法

2014-02-20 22:04:14

#### 龟兔赛跑算法（Floyd判圈算法）

2015-11-12 14:39:27

#### Floyd判圈算法及其证明

2016-11-09 15:41:50

#### Floyd判圈算法(判断是否有环)

2016-10-15 08:47:38

#### Floyd判圈算法

2016-08-28 11:27:57

#### Floyd 判圈 算法

2016-05-08 11:17:26

#### Cycle detection——Floyd判圈算法

2016-07-28 20:10:07

#### 算法-floyd判环(圈)算法

2017-07-03 17:56:44

#### floyd判圈算法

2015-09-23 21:56:35

## 不良信息举报

UVA - 11549 Calculator Conundrum (循环节)(Floyd判圈算法,快慢指针)