算法競賽入門 5.4.1 Cantor的數表

重點:

1.按對角線第i行有i個元素,每個元素的分子+分母=i+1,且當i爲奇數時,分母從1增加到i;當i爲偶數爲,分子從1增加到i;


實現代碼:

#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{
    int n;
    freopen("test.in","r",stdin);

    while(cin >> n){
        int k=0;
        while(k*(k+1)/2 < n){
            k++;
        }
        int m = n - k*(k-1)/2;
        if(k % 2 == 0){

            cout << m << "/"<<k+1-m << endl;
        }
        else{
            cout << k+1-m << "/"<< m << endl;
        }

    }

    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章