Check whether sum of digits at odd places of a number is divisible by K in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number n and another number k, we have to check whether the sum of digits of n at it's odd places (from right side to left side) is divisible by k or not.

So, if the input is like n = 2416 k = 5, then the output will be True as sum of odd placed numbers from right to left is 4 + 6 = 10. Which is divisible by 5.

To solve this, we will follow these steps −

  • total := 0, pos := 1
  • while n > 0 , do
    • if pos is odd, then
      • total := total + (n mod 10)
    • n := quotient of (n / 10)
    • pos := pos + 1
  • if total is divisible by k, then
    • return True
  • return False

Let us see the following implementation to get better understanding −

Example Code

Live Demo

def solve(n, k):
   total = 0
   pos = 1
   while n > 0:
      if pos % 2 == 1:
         total += n % 10
      n = n // 10
      pos += 1
     
   if total % k == 0:
      return True
   return False

n = 2416
k = 5
print(solve(n, k))

Input

2416, 5

Output

True
raja
Published on 16-Jan-2021 04:48:35
Advertisements