1988coder

829. Consecutive Numbers Sum

Feb 26th, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.28 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/consecutive-numbers-sum/submissions/
  2.  
  3. /**
  4.  * Given a number N, we can possibly write it as a sum of 1 number, 2 numbers, 3
  5.  * numbers, 4 numbers and so on. Let's assume the fist number in this series be
  6.  * x. Hence, we should have
  7.  *
  8.  * x + (x+1) + (x+2)+...+ k terms = N
  9.  *
  10.  * kx + k*(k-1)/2 = N implies kx = N - k*(k-1)/2
  11.  *
  12.  * So, we can calculate the RHS for every value of k and if it is a multiple of
  13.  * k then we can construct a sum of N using k terms starting from x.
  14.  *
  15.  * Now, the question arises, till what value of k should we loop for? That's
  16.  * easy. In the worst case, RHS should be greater than 0. That is
  17.  *
  18.  * N - k*(k-1)/2 > 0 which implies k*(k-1) < 2N which can be approximated to
  19.  *
  20.  * k*k < 2N ==> k < sqrt(2N)
  21.  *
  22.  * Time Complexity: O(sqrt(N))
  23.  *
  24.  * Space Complexity: O(1)
  25.  */
  26. class Solution {
  27.     public int consecutiveNumbersSum(int N) {
  28.         if (N <= 0) {
  29.             return 0;
  30.         }
  31.         if (N <= 2) {
  32.             return 1;
  33.         }
  34.  
  35.         int count = 1;
  36.         double endCond = Math.sqrt(2 * N);
  37.  
  38.         for (int k = 2; k < endCond; k++) {
  39.             if ((N - (k * (k - 1) / 2)) % k == 0) {
  40.                 count++;
  41.             }
  42.         }
  43.  
  44.         return count;
  45.     }
  46. }
Add Comment
Please, Sign In to add comment