Cantor表
现代数学的著名证明之一是Georg Cantor证明了有理数是可枚举的。他是用下面这一张表来证明这一命题的:
1/1 1/2 1/3 1/4 1/5 ...
2/1 2/2 2/3 2/4 ...
3/1 3/2 3/3 ...
4/1 4/2 ...
5/1
我们以蛇形给上表的每一项编号。第1项是1/1,然后是1/2,2/1,3/1,2/2...
输入:整数n(1<=n<=10)
输出:表中的第N项
样例:
input: n=7
output: 1/4
[分析]
抓住规律,奇数行分子从1开始递增,分母递减;偶数行分母从1开始递增,分子递减;
对任一n,先确定它位于第几行,即找到最大的X,使得X(X+1)<2n,再分奇偶性进行考虑。
using
System;
class Cantor
... {
static void Main(string[] args)
...{
int count = 0, max = 0, n = 1;
int.TryParse(Console.ReadLine(), out n);
while (n != 0)
...{
Calc(n, out count, out max);
int fz = count + n - max, fm = max + 1 - n;
Console.WriteLine(count % 2 != 0 ? fm + "/" + fz : fz + "/" + fm);
int.TryParse(Console.ReadLine(), out n);
}
}
private static void Calc(int n, out int count, out int max)
...{
count = max = 0;
for (int i = 1; i <=n;i++ )
...{
max += i;
if (max >= n)
...{
count = i;
return;
}
}
}
}
class Cantor
... {
static void Main(string[] args)
...{
int count = 0, max = 0, n = 1;
int.TryParse(Console.ReadLine(), out n);
while (n != 0)
...{
Calc(n, out count, out max);
int fz = count + n - max, fm = max + 1 - n;
Console.WriteLine(count % 2 != 0 ? fm + "/" + fz : fz + "/" + fm);
int.TryParse(Console.ReadLine(), out n);
}
}
private static void Calc(int n, out int count, out int max)
...{
count = max = 0;
for (int i = 1; i <=n;i++ )
...{
max += i;
if (max >= n)
...{
count = i;
return;
}
}
}
}