Program to find sum of digits in base K using Python

Converting a number from base 10 to base K and finding the sum of its digits is a common programming problem. We need to repeatedly divide the number by K and sum up all the remainders.

So, if the input is like n = 985 k = 8, then the output will be 12 because the number 985 in octal is 1731, so the digit sum is 1+7+3+1 = 12.

Algorithm

To solve this, we will follow these steps ?

  • Initialize ans := 0

  • while n >= k, do

    • ans := ans + n mod k

    • n := quotient of n/k

  • ans := ans + n

  • return ans

Implementation

Let us see the following implementation to get better understanding ?

def solve(n, k):
    ans = 0
    while n >= k:
        ans = ans + n % k
        n = n // k
    ans = ans + n
    return ans

n = 985
k = 8
print(solve(n, k))

The output of the above code is ?

12

How It Works

The algorithm works by repeatedly extracting the rightmost digit in base K:

  • 985 % 8 = 1 (remainder), 985 // 8 = 123

  • 123 % 8 = 3 (remainder), 123 // 8 = 15

  • 15 % 8 = 7 (remainder), 15 // 8 = 1

  • Since 1 < 8, we add 1 to our sum

  • Total sum: 1 + 3 + 7 + 1 = 12

Example with Different Base

Let's try another example with base 16 (hexadecimal) ?

def solve(n, k):
    ans = 0
    while n >= k:
        ans = ans + n % k
        n = n // k
    ans = ans + n
    return ans

n = 255
k = 16
print(f"Sum of digits of {n} in base {k}: {solve(n, k)}")

# Let's also show the conversion
def convert_to_base(n, k):
    digits = []
    while n >= k:
        digits.append(n % k)
        n = n // k
    digits.append(n)
    return digits[::-1]

print(f"255 in base 16: {convert_to_base(255, 16)}")

The output of the above code is ?

Sum of digits of 255 in base 16: 15
255 in base 16: [15, 15]

Conclusion

This algorithm efficiently converts a decimal number to any base K and sums its digits by using modulo and integer division operations. The time complexity is O(log_k(n)) where n is the input number and k is the target base.

Updated on: 2026-03-25T20:53:44+05:30

802 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements