829.consecutive-numbers-sum.cpp 488 B

123456789101112131415161718
  1. #include <cmath>
  2. class Solution {
  3. public:
  4. int consecutiveNumbersSum(int N) {
  5. // Assume that we pick n elements start from x, then
  6. // for (x + (n - 1) * x) * n / 2 == N,
  7. // ie. n * x + n * (n - 1) / 2 == N.
  8. // Just check for some n, we have valid x.
  9. int cnt = 0;
  10. for (int n = 1; ; n++) {
  11. int nx = N - n * (n - 1) / 2;
  12. if (nx < n) break;
  13. if (nx % n == 0) cnt++;
  14. }
  15. return cnt;
  16. }
  17. };