Program to find sum of digits in base K using Python

PythonServer Side ProgrammingProgramming

Suppose we have a number n in decimal number system (base 10) have another value k, we have to find the sum of the digits of n after converting given number n from base 10 to base k. When we calculate digit sum, we will consider each digit as decimal (base 10) number.

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.

To solve this, we will follow these steps −

  • ans := 0

  • while n >= k, do

    • ans := ans + n mod k

    • n := quotient of n/k

  • ans := ans + n

  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

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

Input

985,8

Output

True
raja
Updated on 29-May-2021 14:15:44

Advertisements