int main() { int nth; while (1) { scanf("%d", &nth); if (nth == 0) break; int sum=0; int i; // part1: find nth-of-dec (10<n<100? 100<n<1000? ...) for (i=1; i<10; i++) { int p = perm(10, i); if ((sum+p) >= nth) break; sum = sum+p; } // part2: get nth number if (i==1) { sum = nth; } else { int bit[16]={0,}; cnt = sum; sum = getNthNum(bit, nth, i, 1); } printf("%d\n", sum); } return 0; }
int getNthNum(int *bit, int nth, int nthOfdec, int depth) { int sum=0; // last digit if (depth > nthOfdec) { cnt++; return 0; } // 1st: [1-9], remain: [0-9] for (int i=(depth==1?1:0); i<10; i++) { if (!bit[i]) { bit[i] = 1; sum = getNthNum(bit, nth, nthOfdec, depth+1); if (cnt == nth) return sum+i*(int)pow(10, nthOfdec-depth); bit[i] = 0; } } return 0; }
void kperm(int num,int search, int pole[]){ int i,*options; search--; if(search==1){ for(i=0 ; i<num ; i++){ pole[i] = (i+1); } } options = (int *)malloc(num*sizeof(int)); for(i=0 ; i<num ; i++){ options[i] = i+1; } for(i=0 ; i<num ; i++){ double help = fact(num-1-i); pole[i] = getNthNum(search/help+1,options,num); search = search%(int)help; } }