We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
2 parents 9c74e93 + 72c28b8 commit 3d06274Copy full SHA for 3d06274
Math/Consecutive_Numbers_Sum/consecutive_numbers_sum.cpp
@@ -0,0 +1,21 @@
1
+// Given a positive integer N, how many ways can we write it as a sum of consecutive positive integers?
2
+
3
+#include <math.h>
4
+#include <assert.h>
5
6
+int consecutiveNumbersSum(int N) {
7
+ int res = 0;
8
+ double NN = N;
9
+ int maxTerms = (int)(sqrt(8 * NN + 1) - 1) / 2;
10
+ for (int n = 1; n <= maxTerms; n++) {
11
+ int temp = N - (n - 1) * n / 2;
12
+ if (temp > 0 && temp % n == 0) res++;
13
+ }
14
+ return res;
15
+}
16
17
+int main() {
18
+ int sum = consecutiveNumbersSum(15);
19
+ assert(sum == 4);
20
+ return 0;
21
0 commit comments