Consecutive Numbers Sum

hard math number-theory

Problem

Given an integer n, return the number of ways to write n as the sum of consecutive positive integers.

Inputn = 9
Output3
9 = 9 = 4+5 = 2+3+4.

def consecutiveNumbersSum(n):
    count = 0
    k = 1
    while k * (k + 1) // 2 <= n:
        if (n - k * (k - 1) // 2) % k == 0:
            count += 1
        k += 1
    return count
function consecutiveNumbersSum(n) {
  let count = 0, k = 1;
  while ((k * (k + 1)) / 2 <= n) {
    if ((n - (k * (k - 1)) / 2) % k === 0) count++;
    k++;
  }
  return count;
}
class Solution {
  public int consecutiveNumbersSum(int n) {
    int count = 0;
    for (int k = 1; (long)k * (k + 1) / 2 <= n; k++) {
      if ((n - k * (k - 1) / 2) % k == 0) count++;
    }
    return count;
  }
}
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
    int consecutiveNumbersSum(int n) {
        int count = 0;
        for (int k = 1; (long long)k * (k + 1) / 2 <= n; k++) {
            if ((n - k * (k - 1) / 2) % k == 0) count++;
        }
        return count;
    }
};
Time: O(sqrt(n)) Space: O(1)