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 then 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 integert (1 ≤ t ≤ 200), the number of test cases. Each test case contains two integersn (1 ≤ n ≤ 9) and k (0 ≤ k < 10n) wheren 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 99OUTPUT
9 99
Calgary Collegiate Programming Contest 2008
经验教训:思考问题的解决方法前,先要根据已知条件推断出问题的特点和性质。例如本题中,计算器能够显示的数字最多是n位,所能表示的数字的个数是有限的,那么按照对k求平方,然后取前n位数的方法,重复下去,总有一个时候,出现一个重复的数,这个数就是循环节。
//利用STL中的set来寻找循环节
#include <iostream>
#include <cstdio>
#include <set>
#include <cmath>
using namespace std;
//#define LOCAL
#ifdef LOCAL
#define TYPE __int64
#else
#define TYPE long long
#endif
int HighNDigits(int n, TYPE k)
{
int len = floor(log10(k)) + 1;
if (len > n)
{
len -= n;
int m = 1;
while (len-- != 0)
{
m *= 10;
}
return (int)(k / m);
}
return (int)k;
}
int main(void)
{
int ncases;
cin >> ncases;
while (ncases-- != 0)
{
int n, k;
cin >> n >> k;
int max = k;
set<int> s;
while (s.find(k) == s.end())
{
s.insert(k);
if (k > max)
{
max = k;
}
k = HighNDigits(n, (TYPE)k*k);
}
cout << max << endl;
}
return 0;
}
//Floyd判圈算法
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
//#define LOCAL
#ifdef LOCAL
#define TYPE __int64
#else
#define TYPE long long
#endif
int HighNDigits(int n, TYPE k)
{
int len = floor(log10(k)) + 1;
if (len > n)
{
len -= n;
int m = 1;
while (len-- != 0)
{
m *= 10;
}
return (int)(k / m);
}
return (int)k;
}
int main(void)
{
int ncases;
cin >> ncases;
while (ncases-- != 0)
{
int n, k;
cin >> n >> k;
int k1 = k, k2 = k, max = k;
//k1每次向前走一步,k2每次向前走两步,如果存在循环,
//k2最终会与k1相遇,这时k2已经走过了所有的数字,求出max即可
do
{
k1 = HighNDigits(n, (TYPE)k1*k1);
k2 = HighNDigits(n, (TYPE)k2*k2);
if (k2 > max) max = k2;
k2 = HighNDigits(n, (TYPE)k2*k2);
if (k2 > max) max = k2;
} while (k2 != k1);
cout << max << endl;
}
return 0;
}

本文讨论了使用计算器连续平方操作直到数值溢出,只显示最显著数字并清除错误,探究给定数字n和起始数k时能得到的最大数值。通过分析循环节和使用STL中的set数据结构来解决此问题。
432

被折叠的 条评论
为什么被折叠?



