《程序员》2008年第1期"算法擂台" - Cantor表解答
2008-01-16 14:11
369 查看
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;
}
}
}
}
现代数学的著名证明之一是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;
}
}
}
}
相关文章推荐
- 《程序员》2008年第1期"算法擂台" - Cantor表解答
- 《程序员》2008年第1期"算法擂台" - Cantor表解答
- 《程序员》2008年第2期"算法擂台" - 微积分习题解答
- 2008年06期算法擂台解答
- 程序员杂志07年12月算法擂台时间表达的解答
- 用LoadRunner来录制的时候刚开始就出现了“Explore.exe 应用程序错误"一直找不到解答的方法?
- 当您使用 Visual c + + 2008年编译器的错误消息:"致命错误 C1859"
- 程序员如何在"小公司成长"和"大公司学习"
- 我来介绍一下"反向传播学习算法"和"梯度下降法"
- 我看Buddy(伙伴)算法-到底是怎么"找朋友"的
- [原]反对网抄,没有规则可以创建目标"install" 靠谱解答
- 说到做到,贴个"70后男程序员的成长经历"
- 程序员保"胃"大决战 ......看来要多吃枣子了,健胃补血,滋养强壮。
- 程序员之---C语言细节12(指针和数组细节,"//"的可移植性说明)
- 程序员升级项目经理后的"管理之痒"
- "程序员",可悲的职业
- 【转载】&quot;一致性hash&quot;算法与server列表维护(备忘)
- 程序员如何在"小公司成长"和"大公司学习"
- hiho一下 第三周 "KMP"算法
- 程序员的七宗"罪"