VOOZH about

URL: https://www.geeksforgeeks.org/dsa/summing-the-sum-series/

⇱ Summing the sum series - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Summing the sum series

Last Updated : 11 Jul, 2025

Defined a function that calculates the twice of sum of first N natural numbers as sum(N). Your task is to modify the function to sumX(N, M, K) that calculates sum( K + sum( K + sum( K + ...sum(K + N)...))), continuing for M terms. For a given N, M and K calculate the value of sumX(N, M, K)
Note: Since the answer can be very large, print the answer in modulo 10^9 + 7.
Examples: 
 

Input: N = 1, M = 2, K = 3 
Output: 552 
For M = 2 
sum(3 + sum(3 + 1)) = sum(3 + 20) = 552.
Input: N = 3, M =3, K = 2 
Output: 1120422 
For M = 3 
sum(2 + sum(2 + sum(2 + 3))) = sum(2 + sum(2 + 30)) = sum(2 + 1056) = 1120422. 
 


 

Recommended Practice


Approach: 
 

  • Calculate value of sum(N) using the formula N*(N + 1).
  • Run a loop M times, each time adding K to the previous answer and applying sum(prev_ans + K), modulo 10^9 + 7 each time.
  • Print the value of sumX(N, M, K) in the end.


Below is the implementation of the above approach: 
 


Output: 
552

 

Time Complexity: O(M)

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

Comment