题意:
一个数k,让它一直平方一直平方,它只能显示n位数,求这个n为数最大为多少。
思路:
我们可以得到,这个数将出现循环,所以可用set容器中的count函数检测某元素在此前是否出现过,一直获得下一个数,保留最大值即可。
代码:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <set>
#include <cstring>
#include <algorithm>
using namespace std;
int arr[100];
int Next(int n, int k) {
if (!k)
return 0;
long long k2 = (long long)k*k;
memset(arr, 0, sizeof(arr));
int l = 0;
while(k2 > 0) {
arr[l++] = k2 % 10;
k2 = k2 / 10;
}
if (l < n)
n = l;
int i = 0; k = 0;
while (i<n){
k = k * 10 + arr[--l];
i++;
}
// printf("%d\n",k);
return k;
}
int main(){
int cas;
scanf("%d", &cas);
while (cas--) {
int n, k;
scanf("%d%d", &n, &k);
set<int> st;
int ans = k;
while (!st.count(k)) {
st.insert(k);
if (ans < k)
ans = k;
k = Next(n, k);
}
printf("%d\n", ans);
}
return 0;
}