Given an integer n
, return the number of ways you can write n
as the sum of consecutive positive integers.
Example 1:
Input: n = 5 Output: 2 Explanation: 5 = 2 + 3
Example 2:
Input: n = 9 Output: 3 Explanation: 9 = 4 + 5 = 2 + 3 + 4
Example 3:
Input: n = 15 Output: 4 Explanation: 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5
Constraints:
1 <= n <= 109
This problem asks to find the number of ways a given integer n
can be expressed as the sum of consecutive positive integers. The solution uses a mathematical approach to efficiently solve this problem.
Mathematical Derivation:
Let's represent the sum of consecutive positive integers as:
n = a + (a+1) + (a+2) + ... + (a+k-1)
where:
a
is the first term in the sequence (a positive integer).k
is the number of terms in the sequence (also a positive integer).This is an arithmetic series, and its sum can be expressed as:
n = k * (2a + k - 1) / 2
Multiplying both sides by 2, we get:
2n = k * (2a + k - 1)
Rearranging the equation to solve for a
:
2a = (2n / k) - k + 1
a = (2n / k - k + 1) / 2
Since a
must be a positive integer, this equation implies the following conditions:
k
must be a divisor of 2n
: 2n
must be divisible by k
without any remainder.2n/k - k + 1
must be even: This ensures that a
is an integer. This is equivalent to checking if 2n/k
and k
have the same parity (both even or both odd).Algorithm:
The algorithm iterates through possible values of k
(the number of terms). For each k
, it checks if the two conditions above are met. If both conditions are true, it means we've found a valid way to express n
as a sum of k
consecutive positive integers. The iteration continues until k * (k + 1) > 2n
, because beyond this point, k
would be too large to be a valid number of terms.
Time and Space Complexity:
2n
, which is approximately O(√n).Code Implementation (Python):
class Solution:
def consecutiveNumbersSum(self, n: int) -> int:
n <<= 1 # Equivalent to n *= 2 (bitwise left shift for efficiency)
ans, k = 0, 1
while k * (k + 1) <= n:
if n % k == 0 and (n // k - k + 1) % 2 == 0:
ans += 1
k += 1
return ans
The other languages (Java, C++, Go, TypeScript) follow a similar structure, efficiently implementing the algorithm described above. The bitwise left shift (n <<= 1
) is a common optimization for multiplying by 2.
This approach provides an efficient solution to the problem by leveraging mathematical properties to reduce the search space and avoid unnecessary computations.