Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a function that finds number of divisible digits given two parameters

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have two problems.

  1. Your while condition is wrong. You’ll stop as soon as you get to a 0 digit. It should be while n != 0:.
  2. 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading