Advertisement
Guest User

x mod((2^n)-1) by single digit sum

a guest
Nov 20th, 2018
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.12 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. #define MAX_DIG   128 //maximum digits in any base
  5. #define MAX_BASES 16 //maximum number of bases stored
  6.  
  7.  
  8. typedef unsigned long long uint;
  9. typedef long long sint;
  10.  
  11. typedef struct {
  12.   uint N; //number of digits
  13.   uint d[MAX_DIG]; //digits of a number
  14.   uint r; //remainder, d mod(base-1)
  15. } numb;
  16.  
  17. void print_numb(numb* n)
  18. {
  19.     //print backwards
  20.     if (n->N==0) {
  21.         printf("0");
  22.     } else {
  23.         for(sint i=n->N-1; i>=0; i--) printf("%u_",n->d[i]);
  24.     }
  25. }
  26.  
  27. int main(void)
  28. {  
  29.    //todo:malloc for n (Nb) and for d (Nd), maybe not needed
  30.    numb n[MAX_BASES];  //number table for all bases
  31.    const uint x=0xe27efc30f694;
  32.    uint xtmp=x;
  33.    uint Nb=0;
  34.    uint N=0;    //number of calculated bases
  35.    
  36.    while(xtmp!=1) { //get msb bit position
  37.        xtmp>>=1;
  38.        Nb++;
  39.    }
  40.    
  41.    printf("x=%u,Nb=%u:\r\n",x,Nb);
  42.    
  43.    //base is index of n
  44.    //x mod(base-1) is in n['i'].r
  45.    for(uint base=2; base<Nb+1; base<<=1) {   //base2^N
  46.         uint r=0;
  47.         uint cd=0;
  48.         uint pos_i=log2(base);
  49.         xtmp=x;
  50.        
  51.         printf("\r\nbase=%u:\r\n",base);
  52.        
  53.         for(int pos=0; pos<Nb; pos+=pos_i) {
  54.             uint d=xtmp&(base-1); //get digit in base
  55.            
  56.             xtmp>>=pos_i;
  57.             printf("N=%u,cd=%u,d=%u\r\n",N,cd,d);
  58.            
  59.             n[N].d[cd]=d;
  60.             r+=d;   //sum of digits is remainder x mod(base-1)
  61.            
  62.             if(r>=base) r-=base-1;  //modulo sum
  63.            
  64.             cd++;
  65.         }
  66.        
  67.         //note
  68.         if (r==base-1) r=0; //0 equivalent to base-1 when doing mod(base-1)
  69.         //
  70.        
  71.         n[N].N=cd;
  72.         n[N].r=r;
  73.        
  74.         N++;
  75.    }
  76.    
  77.    //todo: display column as base, row as digits
  78.    printf("\r\n\Displaying all values:\r\n");
  79.    printf("x=%u,N=%u,Nb=%u:\r\n\r\n",x,N,Nb);
  80.    
  81.    for(int i=0; i<N;i++) {
  82.        uint base=1<<(i+1);
  83.        
  84.        printf("base%u:",base);
  85.        print_numb(n+i);
  86.        printf(",r=%u",n[i].r);
  87.    
  88.        if(n[i].r==x%(base-1)) printf("   ...OK\r\n");
  89.        else printf("   ...FAILED, r=%u\r\n",x%(base-1));
  90.    }
  91.    
  92.     return 0;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement