Advertisement
Guest User

Fun with binary

a guest
Nov 12th, 2012
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.02 KB | None | 0 0
  1.     #!/usr/bin/rdmd
  2.      
  3.     import std.math, std.stdio, std.algorithm;
  4.      
  5.     long[40][40] choose;
  6.     long[40][40] choose_at_most;
  7.      
  8.     long fun(long n,long m){
  9.       long dig=1<<30;
  10.       long pos=31;
  11.       long res=0;
  12.      
  13.       while (pos){
  14.         if (choose_at_most[pos-1][m] <= n) {
  15.           n -= choose_at_most[pos-1][m];
  16.           res += dig;
  17.           --m;
  18.         }
  19.         dig>>=1;
  20.         pos--;
  21.       }
  22.      
  23.       return res;
  24.     }
  25.      
  26.     string binary(long n, bool trail=true){
  27.       return n? binary(n/2,false) ~ (n&1?'1':'0'): trail? "0": "";
  28.     }
  29.      
  30.     void main(){
  31.       choose[0][0]=1;
  32.      
  33.       for (int i=0; i<40; i++)
  34.         for (int j=0; j<40; j++)
  35.           choose[i][j]=(i?choose[i-1][j]+(j?choose[i-1][j-1]:0):j==0),
  36.           choose_at_most[i][j]=choose[i][j]+(j?choose_at_most[i][j-1]:0);
  37.      
  38.       writeln(choose_at_most[0][0]);
  39.      
  40.       for (int i=0; i<50; i++){
  41.         writefln("%3d = %s",cast(int)fun(i,3),fun(i,3).binary);
  42.       }
  43.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement