Search code examples
c++cradix

How to compare numbers in any base


I have been trying to compare two numbers of any base B without first changing them into decimal. Is there a way to do it?

I was able to do it by converting them into decimal. This is how i did it (on base 17):

 for(i=strlen(s)-1;i>=0;i--)
 {
     if(s[i]>='A'&&s[i]<='G')
         s[i]=s[i]-'A'+ 10;
     else
         s[i]=s[i]-'0';

     int z=(int)s[i];

     a+=z*pow(17,j);
     j++;
 }

Solution

  • Numbers are compared by their value. If their notation is different (in terms of base), digits in the same places means something else. For instance:

    10 [10] > 1000 [2]
    10 [10] < 10000 [2]
    

    I guess the only way to compare two values in different bases is to convert them to the common base and compare afterwards.

    For given number n consisting of digits d = d_k d_{k-1} ... d_1 d_0 in a base b, you can evaluate the value of number using the following formula:

    value = sum_{i=0}^{k} d_{i}*b^i