Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the length needed to represent an integer in an arbitrary base

I have the length of a representation of an integer in an arbitrary base. Say the length is 15, and the base is 36. I'd then like to work out how long a representation of said integer would be in another arbitrary base. i.e, converting to base 2 might result in a length of 68.

I know it's along the lines of the below, but I can't quite get my head around what I need to floor and ceil, and I'm getting some results that are way off:

length * log(fromBase) / log(toBase)
like image 443
Max Avatar asked Jan 23 '13 03:01

Max


People also ask

How do you find the length of an integer?

We can multiply a number 1 by 10 until it becomes greater than the number n. Each time we multiply by 10, we increment a variable count by 1. The final value of the count gives the length of the integer n.

How do you find the length of an integer in Python?

To get the length of an integer in Python:Use the str() class to convert the integer to a string, e.g. result = str(my_int) . Pass the string to the len() function, e.g. len(my_str) . The len() function will return the length of the string.

How do you find the length of an integer in C++?

The size of int[] is basically counting the number of elements inside that array. To get this we can use the sizeof() operator. If the array name is passed inside the sizeof(), then it will return total size of memory blocks that are occupied by the array.

How do you find the length of a number in Java?

Perhaps the easiest way of getting the number of digits in an Integer is by converting it to String, and calling the length() method. This will return the length of the String representation of our number: int length = String. valueOf(number).


1 Answers

Following a Mathematica-like syntax, let

Log[b,n]

represent the logarithm to base b of n. Let Log[n] represent the natural logarithm of n.

Then the ratio

Log[b1,n]/Log[b2,n]

is constant, and equal to

Log[b2]/Log[b1]

This ratio is a multiplier for calculating the number of digits in base b1 from the number of digits in base b2 (or vice-versa if you see things that way). For the example in the question, a 15-digit base-36 number will need

15*Log[36]/Log[2] == 77.5489

base-2 digits. This is, of course, precisely what you have in your question. You only need to round the final answer up to the next integer.

I'm not sure, of course, why you seem to be getting some results that are way off.

like image 8
High Performance Mark Avatar answered Oct 06 '22 23:10

High Performance Mark