We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Consecutive Numbers Sum

Number: 856

Difficulty: Hard

Paid? No

Companies: DE Shaw, Bloomberg


Problem Description

Given a positive integer n, determine the number of ways n can be represented as the sum of one or more consecutive positive integers.


Key Insights

  • Any sequence of consecutive numbers can be expressed in terms of its starting number and length.
  • For a sequence starting at a and having length k, the sum is given by: a + (a+1) + ... + (a+k-1) which equals ka + k(k-1)/2.
  • Rearranging the sum to equal n gives: a = (n - k*(k-1)/2) / k. For a valid sequence, a must be a positive integer.
  • We iterate over possible values of k (starting with 1) until k*(k-1)/2 is less than n.
  • The main challenge is to efficiently enumerate k values while ensuring the arithmetic check for integer a.

Space and Time Complexity

Time Complexity: O(√n) since the maximum possible value of k scales roughly with the square root of n. Space Complexity: O(1) as only a few variables are maintained.


Solution

The problem is solved by converting the requirement of consecutive summation into an equation based on the starting integer a and the number of terms k. For each k, compute a = (n - k*(k-1)/2) / k. If the result is a positive integer, then a valid sequence is found. The algorithm iterates over possible values of k until the part subtracted, k*(k-1)/2, exceeds n. This approach eliminates the need for nested loops and ensures efficient execution given the constraint (n can be as large as 10^9).


Code Solutions

# Python solution for Consecutive Numbers Sum

def consecutiveNumbersSum(n):
    count = 0  # Initialize counter for valid sequences
    k = 1      # Start with sequence length 1
    # Iterate while k*(k-1)/2 is less than n (ensuring a remains positive)
    while k * (k - 1) // 2 < n:
        # Calculate numerator for a: (n - k*(k-1)/2)
        numerator = n - k * (k - 1) // 2
        # Check if a is an integer and positive by verifying divisibility by k
        if numerator % k == 0:
            a = numerator // k  # Find the starting number of the sequence
            if a > 0:
                count += 1  # Valid sequence found
        k += 1  # Increase sequence length for next iteration
    return count

# Example usage:
print(consecutiveNumbersSum(5))  # Output: 2
print(consecutiveNumbersSum(9))  # Output: 3
print(consecutiveNumbersSum(15)) # Output: 4
← Back to All Questions