Advertisement
Ctyderv

binomial

Feb 4th, 2022 (edited)
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.02 KB | None | 0 0
  1. #include <inttypes.h>
  2. #include <stdbool.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6.  
  7. #define MAXLEN 251
  8. #define BASE 1e9
  9.  
  10. typedef uint32_t* bInt;
  11.  
  12. bInt _binit( uint16_t len) {
  13.     bInt num = (bInt)calloc( MAXLEN, sizeof(uint32_t));
  14.     num[0] = 1;
  15.  
  16.     return num;
  17. }
  18.  
  19. bInt binit() {
  20.     return _binit(MAXLEN);
  21. }
  22.  
  23. char* bprint( const bInt num) {
  24.     uint16_t i = num[0];
  25.  
  26.     char* buff = (char*)calloc( ( i ? 9 * i : 1) + 1, sizeof(char));
  27.     char  aux[10] = {0};
  28.     buff[0] = '\0';
  29.  
  30.     sprintf( aux, "%d", ( i ? num[i--] : 0));
  31.     strcat( buff, aux);
  32.  
  33.     while( i > 0) {
  34.         sprintf( aux, "%09d", num[i--]);
  35.         strcat( buff, aux);
  36.     }
  37.  
  38.     return buff;
  39. }
  40.  
  41. bInt copy( const bInt num) {
  42.     bInt cnum = binit();
  43.     memcpy( cnum, num, sizeof(uint32_t) * MAXLEN);
  44.    
  45.     return cnum;
  46. }
  47.  
  48. bInt add( const bInt a, const bInt b) {
  49.     bInt c = copy( a[0] >= b[0] ? a : b);
  50.     const bInt d =  a[0] < b[0] ? a : b;
  51.     uint16_t i = 1;
  52.    
  53.     uint32_t t = 0;
  54.     while( i <= d[0] || t) {
  55.         c[i] += t + d[i];
  56.         if( t = (c[i] >= BASE))
  57.             c[i] -= BASE;
  58.        
  59.         ++i;
  60.     }
  61.  
  62.     if( c[c[0] + 1])c[0]++;
  63.     return c;
  64. }
  65.  
  66. bInt binomial( const uint16_t n, const uint16_t k) {
  67.     bInt* a = (bInt*)calloc( n + 1, sizeof(bInt));
  68.     bInt* b = (bInt*)calloc( n + 1, sizeof(bInt));
  69.  
  70.     for( uint16_t i = 0; i <= n; ++i)
  71.         a[i] = binit(), b[i] = binit();
  72.     a[1][1] = 1;
  73.  
  74.     for( uint16_t line = 1; line <= n; ++line) {
  75.         for( uint16_t i = 1; i <= line; ++i) {
  76.             free( b[i]);
  77.             b[i] = add( a[i - 1], a[i]);
  78.         }
  79.  
  80.         bInt* aux = a; a = b; b = aux;
  81.     }
  82.  
  83.     bInt res = copy( a[k]);
  84.  
  85.     for( uint16_t i = 0; i <= n; ++i)
  86.         free( a[i]), free( b[i]);
  87.  
  88.     return res;
  89. }
  90.  
  91. int main( int argc, char* argv[]) {
  92.     uint16_t n, k;
  93.     scanf( "%" SCNu16 " %" SCNu16, &n, &k);
  94.  
  95.     bInt bc = binomial( n + 1, k + 1);
  96.     printf( "%s\n", bprint( bc));
  97.     free( bc);
  98.  
  99.     return 0;
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement