Skip to content

Commit 3d06274

Browse files
Merge pull request #213 from Fly-Style/math-cons
Add Consecutive Numbers Sum (Math) problem solution
2 parents 9c74e93 + 72c28b8 commit 3d06274

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)