VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-arithmetic-progressions-having-sum-n-and-common-difference-equal-to-1/

⇱ Count Arithmetic Progressions having sum N and common difference equal to 1 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count Arithmetic Progressions having sum N and common difference equal to 1

Last Updated : 23 Jul, 2025

Given an integer N, the task is to count all arithmetic progression with common difference equal to 1 and the sum of all its elements equal to N.

Examples:

Input: N = 12
Output: 3
Explanation: 
Following three APs satisfy the required conditions:

  • {3, 4, 5}
  • {−2, −1, 0, 1, 2, 3, 4, 5}
  • {−11, −10, −9, …, 10, 11, 12]}

Input: N = 963761198400
Output: 1919

Approach: The given problem can be solved using the following properties of AP:

  • The sum of an AP series having N terms with first term as A and common difference 1 is given by the formula S = (N / 2 )* ( 2 *A + N − 1).
  • Solving the above equation:

S = N / 2 [2 *A + N − 1].

Rearranging this and multiplying both sides by 2
=> 2 * S = N * (N + 2 * A − 1)

Rearranging further
=> A = ((2 * N / i ) − i + 1) / 2.

Now, iterate over all the factors of 2 * N, and check for each factor i, whether (2 * N/i) − i + 1 is even or not.

Follow the steps below to solve the problem:

  • Initialize a variable, say count, to store the number of AP series possible having given conditions.
  • Iterate through all the factors of 2 * N and for every ith factor, check if (2 * N / i) − i + 1 is even.
  • If found to be true, increment the count.
  • Print count - 1 as the required answer, as the sequence consisting only of N needs to be discarded.

Below is the implementation of the above approach:

 
 


Output: 
1919

 

Time Complexity: O(√N)
Auxiliary Space: O(1) 

Comment