简体   繁体   中英

Efficient algorithm to find the count of numbers that are divisible by a number without a remainder in a range

Let's say I have two numbers: 6 and 11 and I am trying to find how many numbers between this range are divisible by 2 (3, in this case).

I have this simple code right now:

def get_count(a, b, m):
    count = 0

    for i in range(a, b + 1):
        if i % m == 0:
            count += 1

    return count

Its order of growth is linear, O(N), I believe.

I was wondering if there is a faster algorithm with a constant O(1) performance, or a mathematical formula.

I don't expect a direct answer. The name of such an algorithm would be awesome.

Thank you.

((b - b%m) - a)//m+1 seems to work for me. I doubt it has a name. Another formula that seems to work is (b//m) - ((a-1)//m) .

Sample python3 program:

def get_count(a, b, m):
    return (((b - (b % m)) - a) // m) + 1

for i in range(5, 8):
    for j in range(10, 13):
        print(get_count(i, j, 2), end=" ")
    print()

You are counting even numbers. Let's write o for odd, E for even.

If the sequence has an even count of numbers, it is either oEoE...oE or EoEo...Eo , ie one half of numbers is always even. If there is odd count of numbers, you can check the first number (or last one) separately and the rest is the known case discussed first.

def count_even(start, end):
    # assert start <= end
    len = end - start
    len2, r = divmod(len, 2)
    if r and start % 2 == 0:
        len2 += 1
    return len2

To find the count of all numbers between 0 and n that are divisible by two. you can use the bitwise operation called right shift;

c = a >> 1;

10 >> 1 is equivalent to floor(10/2)

You can subtract the two resultant numbers and get numbers between any range.

This will work in O(1). Hope this helps.

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