So I want to create a function that takes two ints: n and m. I want the function to return the number of digits in n that are divisible by m. A couple special cases, if one of the digits in n is 0 then it will count it as divisible. I am trying to do this by manipulating n itself but am not sure how to effectively loop through each number of the int to check if it is divisible by m. Here's what I have so far:
def divisible_nums(n, m):
num_divisible = 0
while n % 10 in range(1,10):
last_digit = n % 10
if last_digit / m == 0:
num_divisible = 1
n = n // 10
else:
n = n // 10
return num_divisible
It just keeps returning 0, any ideas?
CodePudding user response:
You have two problems.
- Your
while
condition is wrong. You'll stop as soon as you get to a 0 digit. It should bewhile n != 0:
. - Your test for the last digit being divisible by
m
is wrong, you have to use%
, not/
.
def divisible_nums(n, m):
num_divisible = 0
while n != 0:
last_digit = n % 10
if last_digit % m == 0:
num_divisible = 1
n = n // 10
return num_divisible
Also, n = n // 10
is the same in both the if
and else
, so take it out of the condition and move it into the main body of the loop.