CODEVITA C PROBLEMS SOLUTION
CODEVITA C PROBLEMS SOLUTION
Output:
2
Explanation:
5 = 5 = 2 + 3
Example 2:
Input:
9
Output:
3
Explanation:
9 = 9 = 4 + 5 = 2 + 3 + 4
Example 3:
Input:
15
Output:
4
Explanation:
15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5
Note:1 <= N <= 10 ^ 9.
Thoughts:
Code 1
class 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 res
Code 2
class 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;
}
};
Input: N = 15
Output: 3
Explanation:
15 can be represented as:
1. 1 + 2 + 3 + 4 + 5
2. 4 + 5 + 6
3. 7 + 8
Input: N = 10
Output: 1
int main() {
if (x < y) {
if ((i % 2) != 0) {
return 0;
}
Output:
Input a pair of numbers (for example 10,2):
Input first number of the pair: 10