Guest User

mod2^n by sum

a guest
Nov 20th, 2018
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.61 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. #define MAX_DIG 32 //maximum digits in any base
  5.  
  6. typedef struct {
  7.   int x; //number in base10
  8.   int N; //number of digits
  9.   int b; //base for d
  10.   int d[MAX_DIG]; //digits of a number
  11.   int r; //remainder, d mod(b-1)
  12. } numb;
  13.  
  14. void sum_d(numb* n) //=n.d mod(n.b-1)
  15. {
  16.   n->r=0;
  17.  
  18.   for (int i=0; i<n->N; i++) {
  19.     n->r+=n->d[i];
  20.  
  21.     if(n->r>=n->b) {
  22.       n->r-=(n->b-1);
  23.     }
  24.   }
  25.  
  26.   if (n->r==n->b-1) n->r=0;
  27. }
  28.  
  29. void to_base(int b, numb* n) //b=2^i, where i=1,2,3,...
  30. {
  31.   //TODO:convert to baseb more easily
  32. }
  33.  
  34. void gen_numb(int b, int Nd, int x, numb* n) //b=2^i, where i=1,2,3,4,..
  35. {
  36.   n->N=Nd; //number of digits in base b
  37.   n->b=b;
  38.   int Nb=log2(b); //number of bits per digit in base b
  39.   int i = 0;
  40.   int j = 0;
  41.  
  42.   for (i=0; i < Nd; i++) {
  43.     n->d[i]=(x & ((b-1) << j)) >> j;
  44.  
  45.     j+=Nb;
  46.   }
  47.  
  48.   n->x=x;
  49.  
  50.   sum_d(n);
  51. }
  52.  
  53. int main(void)
  54. {
  55.     #define N_VALS 3
  56.     #define N_BASE 5
  57.    
  58.     const int bx[N_BASE] = {64,32,16,8,4}; //base of x
  59.     const int x[N_VALS] = {791,135727,478};
  60.     const int Nd[N_VALS][N_BASE] = {  //Nd for x[i] in all bases
  61.         {2,2,3,4,5},
  62.         {3,4,5,6,9},
  63.         {2,2,3,3,5}
  64.     }; //number of digits in x
  65.  
  66.     numb n;
  67.    
  68.     for(int i=0; i<N_VALS; i++) {
  69.         for(int j=0; j<N_BASE; j++) {
  70.             gen_numb(bx[j],Nd[i][j],x[i],&n);
  71.            
  72.             printf("x=%u,b=%u,r=%u",x[i],bx[j],n.r);
  73.            
  74.             if (n.r == x[i]%(bx[j]-1)) printf("   ...OK\r\n");
  75.             else printf("   ...FAIL, r=%u\r\n",x[i]%(bx[j]-1));
  76.         }
  77.     }
  78.    
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment