Arithmetic mean of numbers in an interval divisible by given c

40 Views Asked by At

Studying Python, I was solving an algorithmic problem:
find the arithmetic mean of numbers in an interval [a, b] divisible by given c.

Having solved it with loops, I wondered about a simple formula that uses only integer division. I could not find one, even under assumptions of 0 < a <= b, c >0 Here's some solution with minimal use of conditions ( // is integer division and % is reminder):

if a % c == 0:  
    first = a  
else:  
    first = (a // c + 1) * c  
    
last = c * (b // c)  

if first > last:  
    print(0)  
else:
    print((first + last) / 2)   

Perhaps someone will be interested to find a single formula!

1

There are 1 best solutions below

0
On

Finally

foo = - (- a // c)
bar = b // c

if foo == bar + 1:
    result = 'Undefined'
else:
    result = (foo + bar) * c / 2

print(result)