dengxinyi 6 lat temu
rodzic
commit
5c2609ce48
1 zmienionych plików z 18 dodań i 0 usunięć
  1. 18 0
      leetcode/hard/829.consecutive-numbers-sum.cpp

+ 18 - 0
leetcode/hard/829.consecutive-numbers-sum.cpp

@@ -0,0 +1,18 @@
+#include <cmath>
+
+class Solution {
+public:
+    int consecutiveNumbersSum(int N) {
+        // Assume that we pick n elements start from x, then
+        // for (x + (n - 1) * x) * n / 2 == N,
+        // ie. n * x + n * (n - 1) / 2 == N.
+        // Just check for some n, we have valid x.
+        int cnt = 0;
+        for (int n = 1; ; n++) {
+            int nx = N - n * (n - 1) / 2;
+            if (nx < n) break;
+            if (nx % n == 0) cnt++;
+        }
+        return cnt;
+    }
+};