Check if all digits of a number divide it in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number n. We have to check whether all digits of it can divide n or not.

So, if the input is like n = 135, then the output will be True, because (135 / 1 = 135), (135 / 3 = 45) and (135 / 5 = 27).

To solve this, we will follow these steps −

  • val := n
  • while val > 0, do
    • d := val mod 10
    • if n is not divisible by d, then
      • return False
    • val := quotient of (val / 10)
  • return True

Let us see the following implementation to get better understanding −

Example

 Live Demo

def is_divisible(n, d) :
   return d != 0 and n % d == 0
def solve(n) :
   val = n
   while (val > 0) :
      d = val % 10
   if not is_divisible(n, d):
      return False
      val = val // 10
   return True
n = 135
print(solve(n))

Input

135

Output

True
raja
Published on 29-Dec-2020 13:43:36
Advertisements