P1014 [NOIP1999 Popularization Group] Cantor table

Title Description
One of the famous proofs of modern mathematics is Georg Cantor's proof that rational numbers are enumerable. He used the following table to prove this proposition:
Insert picture description here

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

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

Output format
The Nth item in the table.

Input sample

7

Sample output

4/1

Simulate + find the law, just draw the diagonal part in the order of labeling, 1/1 itself is the first diagonal, a total of 1 number. The two numbers 1/2 and 2/1 are the second diagonal, and there are two numbers in total. 3/1,2/2,1/3 is the third diagonal, there are three numbers in total...there are several numbers on the first diagonal. Odd-numbered bars are from upper right to lower left, and even-numbered bars are from lower left to upper right. After determining which diagonal is the number, start looking for the number of this one (labeled from 1), the numerator and denominator are added regularly, the numerator is increased by 1, the denominator is correspondingly subtracted by 1, and the sum is the diagonal Number (the number of numbers on the diagonal)+1
#include <iostream>
using namespace std;

int main() {
    
    
    int n;
    cin >> n;
    long long sum = 0;
    for (int i = 1;; i++) {
    
    
        sum += i;
        if (sum == n) {
    
    
            if (i % 2 == 0)
                cout << i << "/1";
            else
                cout << "1/" << i;
            break;
        } else if (sum > n) {
    
    
            int j = i - 1;
            sum -= i;
            int diff = n - sum;
            if (j % 2 == 1) {
    
    
                cout << diff << "/" << i + 1 - diff;
            } else {
    
    
                cout << i + 1 - diff << "/" << diff;
            }
            break;
        }
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45845039/article/details/112971529