Problem statement

https://leetcode.com/problems/consecutive-numbers-sum/

Solution

We need to find number of solutions in integer numbers of equation: a + a+1 + ... + a+k-1 = N, which can be written as k(2a+k-1) = 2N. Notice, that k < k + 2a - 1 and also these two numbers has different parity. So what we need to find is just number of decomposition of number 2N into two factors, such that sum of these factors has reminder 1 modulo 2. It can be written in very simple way.

Complexity

Time complexity is O(sqrt{N}), space complexity is O(1).

Code

class Solution:
    def consecutiveNumbersSum(self, N):
        ans = 0
        for k in range(1, ceil(sqrt(2*N))):
            if (k + 2*N/k) % 2 == 1:
                ans += 1
        return ans