Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // LeetCode URL: https://leetcode.com/problems/consecutive-numbers-sum/submissions/
- /**
- * Given a number N, we can possibly write it as a sum of 1 number, 2 numbers, 3
- * numbers, 4 numbers and so on. Let's assume the fist number in this series be
- * x. Hence, we should have
- *
- * x + (x+1) + (x+2)+...+ k terms = N
- *
- * kx + k*(k-1)/2 = N implies kx = N - k*(k-1)/2
- *
- * So, we can calculate the RHS for every value of k and if it is a multiple of
- * k then we can construct a sum of N using k terms starting from x.
- *
- * Now, the question arises, till what value of k should we loop for? That's
- * easy. In the worst case, RHS should be greater than 0. That is
- *
- * N - k*(k-1)/2 > 0 which implies k*(k-1) < 2N which can be approximated to
- *
- * k*k < 2N ==> k < sqrt(2N)
- *
- * Time Complexity: O(sqrt(N))
- *
- * Space Complexity: O(1)
- */
- class Solution {
- public int consecutiveNumbersSum(int N) {
- if (N <= 0) {
- return 0;
- }
- if (N <= 2) {
- return 1;
- }
- int count = 1;
- double endCond = Math.sqrt(2 * N);
- for (int k = 2; k < endCond; k++) {
- if ((N - (k * (k - 1) / 2)) % k == 0) {
- count++;
- }
- }
- return count;
- }
- }
Add Comment
Please, Sign In to add comment