cantor的数表

第一项是1/1,第二项是1/2,第三项是2/1,第四项是3/1,第五项是2/2,……。输入n,输出第n项。

一种可行的算法:

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

int main()
{
 int n,k,s;
 while(scanf_s("%d",&n))
 {
  k = (int)floor((sqrt(8.0*n +1) - 1)/2-1e-9)+1;
  s = k*(k+1)/2;
  printf("%d/%d\n",k-s+n,s-n+1);
  system("pause");
 }
 return 0;
}
 

算法原理:先求出k,k满足n<=k(k+1)/2,将数字摆放成三角矩阵即可发现规律。

你可能感兴趣的:(数表,cantor)