Count of sum of consecutives

Posted: 11 Mar, 2021
Difficulty: Hard

PROBLEM STATEMENT

Try Problem

You are given a positive integer 'N.' Your task is to find the number of ways to represent the given number 'N' as the sum of two or more consecutive natural numbers.

Input Format:
The first line contains an integer, ‘T,’ which denotes the number of test cases or queries to be run. Then, the 'T' test cases follow.

The first and the only line of each test case contains one integer 'N', as described in the problem statement.
Output Format:
For each test case, return one integer denoting the number of ways to represent the given number 'N' as the sum of 2 or more consecutive natural numbers.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 100
1 <= N <= 10^8

Time Limit: 1 sec
Approach 1

Approach:

 

In this brute force approach,. We will iterate from 1 to ‘N’ using the iterator i and will check if there is a possible sequence of consecutive positive integers such that their sum is ‘N’, and the ending integer of the consecutive sequence is 'i'. The checking will be done as follows:

  • We know that the ending position is ‘i’. Therefore, we need to find a starting point for the consecutive sequence. Let that integer is 'k'.
  • Now we can say that (i*(i+1))/2 - (j*(j+1))/2 = ‘N’, where ‘j’ = ‘k-1’ (since sum of first n natural numbers is given by the equation (N*(N+1))/2).
  • After simplifying the equation in the above point we will get : (j^2 + j + 2*N - i^2 - i) = 0
  • Now, if there exists a positive integral root for ‘j’ in the above equation, then there is an answer, and we will count this sequence in our answer, or else it is not possible, then we will not count this sequence in the answer.

 

Steps:

  1. Create a variable to store the answer (say, ANS) with 'ANS' = 0.
  2. Run a loop from ‘i’ = 0 to ‘N’ and do:
    1. Create three variables (say A,B and C) and initialize ‘A’ = 1, ‘B’ = 1 and ‘C’ = 2 * ‘N’ - i * i - i.
    2. Create a variable ‘D’ and initialize ‘D’ = B * B - 4*A*C.
    3. Create a variable 'SQROOT' and initialize 'SQROOT' = square root of ‘D’.
    4. Create a boolean variable ‘CHECK’ initialized with false.
    5. If ‘D’ >= 0 and SQROOT * SQROOT == D :
      1. If (-B + SQROOT) is divisible by (2 * A) and (-B + SQROOT) / (2 * A) >= 0 and (i - ((-B + SQROOT) / (2 * A))) >= 2 :
        1. ‘CHECK’ = true
      2. If (-B - SQROOT) is divisible by  (2 * A) and (-B - SQROOT) / (2 * A) >= 0 and (i - ((-B - SQROOT) / (2 * A))) >= 2 :
        1. ‘CHECK’ = true
    6. If ‘CHECK’ is true:
      1. Increment the ‘ANS’ variable by 1.
  3. Finally, return the ‘ANS’ variable.
Try Problem