[LeetCode] Consecutive Numbers Sum

829. Consecutive Numbers Sum

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

  • basic idea from sum [1…n] = n * (n + 1) / 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
int formula(int target, int k) {
return (target / k) + k;
}
bool verify(int target, int k) {
int alpha = formula(target, k);
return alpha & 1;
}
public:
int consecutiveNumbersSum(int n) {
int target = n * 2;
int res = 0;
for(int k = 1; k * k <= target; k++) {
if(target % k == 0 and verify(target, k)) {
res++;
}
}
return res;
}
};
  • build up from this formula
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
int formula(int target, int k) {
return ((target / k) + k - 1) / 2;
}
bool verify(int target, int k) {
int alpha = formula(target, k);
return k * (2 * alpha - k + 1) == target;
}
public:
int consecutiveNumbersSum(int n) {
int target = n * 2;
int res = 0;
for(int k = 1; k * k <= target; k++) {
if(target % k == 0 and verify(target, k)) {
res++;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/22/PS/LeetCode/consecutive-numbers-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.