Luogu P1014Cantor table implemented in java

Luogu P1014Cantor table implemented in java


Title Description One of the famous proofs of
modern mathematics is Georg Cantor's proof that rational numbers are enumerable. He proves this proposition with the following table:

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, …

We number each item in the table above in a zigzag. The first item is 1/1, then 1/2, 2/1, 3/1, 2/2, ...

Input format
Integer N (1 <=N <= 10^7).

Output Format
Item N in the table.

Input and output example
Input 7
Output 1

import java.util.Scanner;
 
public class Main {
    
    
    public static void main(String[] args) {
    
    
        long sum=1;//记录总值
        Scanner scanner=new Scanner(System.in);
        long test=scanner.nextLong();
        long n=1;//记录下一次斜线的长度
        long psum=0;//记录前一个总值
        while(true)//找到输入的值对应的斜线
        {
    
    
            if (test<=sum)
            {
    
    
                break;
            }
            n++;
            psum=sum;
            sum=sum+n;
        }
        long testk=test-psum;//找到当条斜线的对应的下标
       if (n%2==0)
       {
    
    
           System.out.println(String.format("%d/%d", testk,n-testk+1));
       }else {
    
    
           System.out.println(String.format("%d/%d",n-testk+1,testk));
       }
        scanner.close();
    }
}

Guess you like

Origin blog.csdn.net/qq_45451150/article/details/111010836