博客
关于我
P1014_Cantor表 (JAVA语言)
阅读量:151 次
发布时间:2019-02-27

本文共 1030 字,大约阅读时间需要 3 分钟。

为了解决这个问题,我们需要找到Cantor表中的第N项。Cantor表是一个有理数序列,按照特定的规律排列。我们的目标是通过给定的N,确定其对应的分数。

方法思路

  • 确定所在行:Cantor表中的每一行代表不同的分母,行号k的第一个元素的位置可以通过三角数公式来确定。三角数T(k) = k*(k+1)/2表示前k行的最后一个元素的位置。
  • 二分查找行号:使用二分查找来确定行号k,使得T(k) >= N。这个过程确保我们能准确找到N所在的行。
  • 确定位置:找到行号后,计算N在该行中的位置m。分数即为m/k。
  • 解决代码

    import java.util.Scanner;public class P1014_Cantor表 {    public static void main(String[] args) {        Scanner in = new Scanner(System.in);        int n = in.nextInt();        int low = 1;        int high = 200000;        int k_row = 0;        while (low <= high) {            int mid = (low + high) / 2;            long T_mid = (long) mid * (mid + 1) / 2;            if (T_mid < n) {                low = mid + 1;            } else {                high = mid - 1;            }        }        k_row = low;        int m = n - (k_row - 1) * k_row / 2;        System.out.println(m + "/" + k_row);    }}

    代码解释

  • 输入读取:使用Scanner读取输入的整数N。
  • 二分查找行号:通过二分查找确定N所在的行号k_row,使得三角数T(k_row) >= N。
  • 计算位置:计算N在该行中的位置m,分数即为m/k_row。
  • 输出结果:将分子和分母用"/"连接,输出结果。
  • 这种方法确保了高效准确地找到Cantor表中的第N项,并且适用于较大的N值。

    转载地址:http://nwcb.baihongyu.com/

    你可能感兴趣的文章
    Static--用法介绍
    查看>>
    ssm旅游信息管理系统的设计与实现bus56(程序+开题)
    查看>>
    order by rand()
    查看>>
    SSM(Spring+SpringMvc+Mybatis)整合开发笔记
    查看>>
    ViewHolder的改进写法
    查看>>
    Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
    查看>>
    org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
    查看>>
    sql查询中 查询字段数据类型 int 与 String 出现问题
    查看>>
    org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
    查看>>
    org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
    查看>>
    sqlserver学习笔记(三)—— 为数据库添加新的用户
    查看>>
    org.apache.http.conn.HttpHostConnectException: Connection to refused
    查看>>
    org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
    查看>>
    org.apache.ibatis.exceptions.PersistenceException:
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>
    org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    查看>>
    org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
    查看>>
    org.hibernate.HibernateException: Unable to get the default Bean Validation factory
    查看>>