How to calculate the value of the i-th digit in the k-ary representation of a number?

What is a good algorithm for calculating the value of the i-th digit in the k-ary representation of n?

Example:

For the function bitval(int k, int i, int n) :

bitval(5, 4, 9730) = 2 , because in the 5-ary representation of 9730 (302410), the 4th digit (on the right) is 2.

+6
source share
2 answers

Sort of:

 (n / (k ** i)) % k 

(where ** is the exponential operator, and / is the integer (truncating) division). Use (i-1) if you want to dial the numbers on the right, starting at 1 and not starting at 0.

+5
source

The naive algorithm is as follows:

  • Compute the k decimal representation of n . This can be achieved with repeated divisions and modular operations.
  • Return the i -th digit to this view.
-2
source

Source: https://habr.com/ru/post/894676/


All Articles