《程序员》2008年第1期"算法擂台" - Cantor表解答

 

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;
            }

        }

    }

}

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值