简体   繁体   中英

Python: Count divisible numbers from a smaller number WITHOUT string

Say you have a function:

def count_divisible_numbers(n, m):
    ...

This function should calculate how many digits in n are evenly divisible by m .

For example:

>>> n = 668593
>>> m = 3
>>> count_divisible_numbers(n, m)
4

BECAUSE 6, 6, 9, and 3 of 6668593 (n) are divisible by 3 (m).

You can't use str to break apart n into individual parts, and you can ONLY use pythons built-in variables / functions (no imports) WITHOUT recursion.

How would you define this function to get it to produce that result?

NOTE: I'm a self-taught Python programmer who's bulit packages and web apps before, and this was a problem that a student of mine that was in college had that I couldn't figure out how to solve, and it annoyed me.

You can check the ones-place of n by taking the modulus of 10, then use that value to check if evenly divisible by m . Then integer-divide by 10 to move all the digits "over" to work on the next number that is now in the ones-place.

def count_divisble_numbers(n, m):
    total = 0
    while n > 0:
        if (n%10) % m == 0:
            total += 1
        n //= 10
    return total

>>> count_divisble_numbers(668593, 3)
4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM