Check whether product of digits at even places of a number is divisible by K in Python


Suppose we have a number n, and another number k, we have to check whether the product of digits at even places of n is divisible by k or not. Places are started counting from right to left. Right most is at place 1.

So, if the input is like n = 59361, then the output will be True as (1*3*5) is divisible by 3.

To solve this, we will follow these steps −

  • digit_count := digit count of given number n
  • prod := 1
  • while n > 0, do
    • if digit_count is even, then
      • prod := prod * last digit of n
    • n := quotient of (n / 10)
    • digit_count := digit_count - 1
  • if prod is divisible by k, then
    • return True
  • return False

Let us see the following implementation to get better understanding −

Example Code

Live Demo

from math import log10

def solve(n, k):
   digit_count = int(log10(n))+1
   prod = 1
   while n > 0 :
      if digit_count % 2 == 0 :
         prod *= n % 10
        
      n = n // 10
      digit_count -= 1
 
   if prod % k == 0:
      return True
   return False
   
n = 59361
k = 3
print(solve(n, k))

Input

59361, 3

Output

True

Updated on: 16-Jan-2021

73 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements