How to compute value of i-th digit in a k-ary representation of a number?
What is a good algorithm to compute the value of the i-th digit in a 开发者_JAVA百科k-ary representation of a number n?
Example:
For function bitval(int k, int i, int n)
:
bitval(5, 4, 9730) = 2
because in a 5-ary (quinary) representation of the number 9730 (which is 302410) the 4th digit (from the right) is 2.
Something like:
(n / (k ** i)) % k
(where **
is the exponentiation operator and /
is integer (truncating) division) should do it. Use (i-1)
if you want to number the digits from the right starting with 1 rather than starting with 0.
The naive algorithm is as follows:
- Calculate the
k
-ary representation ofn
. This can be achieved with repeated divides and modulo operations. - Return the
i
-th digit in this representation.
精彩评论