829. Consecutive Numbers Sum
Input:
5
Output:
2
Explanation:
5 = 5 = 2 + 3Input:
9
Output:
3
Explanation:
9 = 9 = 4 + 5 = 2 + 3 + 4Last updated
Was this helpful?
Input:
5
Output:
2
Explanation:
5 = 5 = 2 + 3Input:
9
Output:
3
Explanation:
9 = 9 = 4 + 5 = 2 + 3 + 4Last updated
Was this helpful?
Was this helpful?
Input:
15
Output:
4
Explanation:
15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5class Solution:
def consecutiveNumbersSum(self, N: int) -> int:
if N == 1:
return 1
res = 1
for i in range(2, int(N ** .5 + 1)):
if N % i == 0:
if i % 2 == 1: # If i is odd, then we can form a sum of length i
res += 1
j = (N // i) # Check the corresponding N // i
if i != j and j % 2 == 1:
res += 1
if N % 2 == 1: # If N is odd(2k + 1). Then N = k + k + 1, not included above
res += 1
return resclass Solution {
public:
int consecutiveNumbersSum(int N) {
int res = 0;
for(int i=1; i*(i-1)<=2*N; i++) {
if((2*N+i-i*i)%(2*i)==0&&(2*N+i-i*i)/(2*i)>0) {
res++;
}
}
return res;
}
};