Problem C
CALCULATOR CONUNDRUM
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 overflows. When the result overflows, only the n most significant digits are displayed on the screen and an error flag 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?”
Program Input
The first 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 < 10n) where n is the number of digits this calculator can display k is the starting number.
Program Output
For each test case, print the maximum number that Alice can get by repeatedly squaring the starting number as described.
Sample Input & Output
INPUT
2
1 6
2 99
OUTPUT
9 99
#include <stdio.h> #include <string.h> #include <set> #define max(a,b) ((a)>(b)?(a):(b)) using namespace std; int t, n; long long k; set<int> vis; void init() { vis.clear(); scanf("%d%lld", &n, &k); } long long Pow(long long k) { long long ans = 0; long long t = k * k; long long save[20]; int saven = 0; while (t) { save[saven++] = t % 10; t /= 10; } for (int i = saven - 1; i > max(saven - 1 - n, -1); i--) ans = ans * 10 + save[i]; return ans; } int solve() { int ans = 0; while (vis.find(k) == vis.end()) { if (ans < k) ans = k; vis.insert(k); k = Pow(k); } return ans; } int main() { scanf("%d", &t); while (t--) { init(); printf("%d\n", solve()); } return 0; }
floyd判圈法:
#include <stdio.h> #include <string.h> #define max(a,b) ((a)>(b)?(a):(b)) int t, n; long long k; void init() { scanf("%d%lld", &n, &k); } long long Pow(long long k) { long long ans = 0; long long t = k * k; long long save[20]; int saven = 0; while (t) { save[saven++] = t % 10; t /= 10; } for (int i = saven - 1; i > max(saven - 1 - n, -1); i--) ans = ans * 10 + save[i]; return ans; } int solve() { long long k1 = k, k2 = k, ans = k; while (1) { k1 = Pow(k1); k2 = Pow(k2); ans = max(ans, k2); k2 = Pow(k2); ans = max(ans, k2); if (k1 == k2) break; } return ans; } int main() { scanf("%d", &t); while (t--) { init(); printf("%lld\n", solve()); } return 0; }