Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 245
Frank Avatar asked Aug 09 '11 20:08

Frank


1 Answers

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.

like image 103
Greg Hewgill Avatar answered Nov 15 '22 10:11

Greg Hewgill