VOOZH about

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

⇱ Count Arithmetic Progressions having sum S and common difference equal to D - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count Arithmetic Progressions having sum S and common difference equal to D

Last Updated : 23 Jul, 2025

Given two integers S and D, the task is to count the number of Arithmetic Progressions possible with sum S and common difference D.

Examples:

Input: S = 12, D = 1
Output: 4
Explanation: Following 4 arithmetic progressions with sum 12 and common difference 1 are possible:

  1. {12}
  2. {3, 4, 5}
  3. {-2, -1, 0, 1, 2, 3, 4, 5}
  4. {-11, -10, -9, ..., 10, 11, 12}

Input: S = 1, D = 1
Output: 2
Explanation: Following 2 arithmetic progressions with sum 1 and common difference 1 are possible:

  1. {1}
  2. {0, 1}

Approach: The given problem can be solved based on the following observations:

where, 
S is the sum of the AP series, 
a is the first term of the series, 
N is the number of terms in the series, 
d is a common difference

  • After rearranging the above expressions:

=> 2*S = N*(2*a + (N - 1)*d)      ... (1)

=>   ...(2)

  • From the above two expressions:
    • The idea is to consider all the factors of 2*S and check if there exists any factor F such that the product of F and (2*a + (F - 1)*d) is equal to 2 * S. If found to be true, then count that factor for one of the possible AP having the given sum S.
    • If there exists any factor F, such that (D * F - (2 * S / F) + D) is divisible by 2, then count that factor for one of the possible AP having the given sum S.

Follow the steps below to solve the problem:

  • Initialize a variable, say answer, to store the count of APs with sum S and common difference D.
  • Iterate over the range[1, ?2*S] and check if 2 * S is divisible by i, then perform the following steps:
    • If the value of ((2 * S / i) + 1 - i * D) is divisible by 2, then increment answer by 1.
    • If the value of (i * D - S / i + 1) is divisible by 2, then increment answer by 1.
  • After completing the above steps, print the value of answer as the resultant count of APs.

Below is the implementation of the above approach:


Output
4

Time Complexity: O(sqrt(S)) 
Auxiliary Space: O(1),  since no extra space has been taken.

Comment