Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Count Consecutive Summers by vlad.bezden
"""
Positive integers can be expressed as sums of consecutive positive
integers in various ways.
For example, 42 can be expressed as such a sum in four different ways:
(a) 3+4+5+6+7+8+9,
(b) 9+10+11+12,
(c) 13+14+15 and
(d) 42.
As the last solution (d) shows, any positive integer can always be trivially
expressed as a singleton sum that consists of that integer alone.
Compute how many different ways it can be expressed as a sum of consecutive
positive integers.
Input: Int.
Output: Int.
Precondition: Input is always a positive integer.
"""
from itertools import count
def count_consecutive_summers(num: int) -> int:
counter = 0
for i in count(1):
# find middle + half spread = end
end = (num // i) + (i // 2 + 1)
start = end - i
if start <= 0:
break
if sum(range(start, end)) == num:
counter += 1
return counter
if __name__ == "__main__":
assert count_consecutive_summers(42) == 4
assert count_consecutive_summers(99) == 6
assert count_consecutive_summers(105) == 8
assert count_consecutive_summers(1) == 1
assert count_consecutive_summers(2) == 1
print("DONE")
Feb. 16, 2019
Comments: