Cantor数表

cantor数表(算法竞赛入门  p81)

              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

                .

                …..

            输入
             3
             7
             14
             12345
             输出
             2/1
             2/4
             1/4
              59/99

代码实现

#include <stdio.h>
#include <math.h>

int Cantor_2(int n)
{
        int k = (int)floor((sqrt(8.0*n+1)-1)/2-1e-9)+1;
        int s = k*(k+1)/2;
        if(k%2 == 0){
                printf("        %d/%d\n", k-s+n , s-n+1);
        }
        else{
                printf("        %d/%d\n", s-n+1 , k-s+n);
        }
        return 1;
}

int Cantor_1(int n)
{
        int i;
        for(i = 1 ; ; i++){
                if(i*(i+1)/2 >= n){
                        if(i%2 == 0)
                                printf("        %d/%d\n", i+n-i*(i+1)/2 , i*(i+1)/2-n+1);
                        else
                                printf("        %d/%d\n", i*(i+1)/2-n+1 , i+n-i*(i+1)/2);
                        return 1;
                }
        }
        return 0;
}

int main()
{
        int n;
        while(~scanf("%d",&n),n){
                printf("Cantor_1:\n");
                Cantor_1(n);
                printf("Cantor_2:\n");
                Cantor_2(n);
        }
        return 0;
}

 

 

点赞