Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

C Program for cube sum of first n natural numbers

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Print the sum of series 13 + 23 + 33 + 43 + …….+ n3 till n-th term. 

Examples:

Input : n = 5
Output : 225
13 + 23 + 33 + 43 + 53 = 225

Input : n = 7
Output : 784
13 + 23 + 33 + 43 + 53 + 
63 + 73 = 784

Naive Approach:

  1. Define the function sumOfCubes which takes an integer input n.
  2. Declare and initialize a variable sum to 0.
  3. Start a loop with i ranging from 1 to n.
  4. For each iteration of the loop, calculate the cube of i and add it to sum.
  5. After the loop ends, return the value of sum.

C++




#include <iostream>
using namespace std;
 
int sumOfCubes(int n) {
    int sum = 0;
    for(int i = 1; i <= n; i++) {
        sum += i*i*i;
    }
    return sum;
}
 
int main() {
    int n = 5;
    cout << sumOfCubes(n);
    return 0;
}

Output

225

The time complexity is O(n), where n is the input value. 
The auxiliary space is O(1),

An efficient solution is to use direct mathematical formula which is (n ( n + 1 ) / 2) ^ 2 

For n = 5 sum by formula is
       (5*(5 + 1 ) / 2)) ^ 2
          = (5*6/2) ^ 2
          = (15) ^ 2
          = 225

For n = 7, sum by formula is
       (7*(7 + 1 ) / 2)) ^ 2
          = (7*8/2) ^ 2
          = (28) ^ 2
          = 784

C++




// A formula based C++ program to find sum
// of series with cubes of first n natural
// numbers
#include <iostream>
using namespace std;
 
int sumOfSeries(int n)
{
    int x = (n * (n + 1)  / 2);
    return x * x;
}
 
// Driver Function
int main()
{
    int n = 5;
    cout << sumOfSeries(n);
    return 0;
}

Output

225

Time Complexity : O(1) 
Auxiliary Space : O(1) because constant space has been used

How does this formula work? We can prove the formula using mathematical induction. We can easily see that the formula holds true for n = 1 and n = 2. Let this be true for n = k-1.

Let the formula be true for n = k-1.
Sum of first (k-1) natural numbers = 
            [((k - 1) * k)/2]2

Sum of first k natural numbers = 
          = Sum of (k-1) numbers + k3
          = [((k - 1) * k)/2]2 + k3
          = [k2(k2 - 2k + 1) + 4k3]/4
          = [k4 + 2k3 + k2]/4
          = k2(k2 + 2k + 1)/4
          = [k*(k+1)/2]2

The above program causes overflow, even if result is not beyond integer limit. Like previous post, we can avoid overflow upto some extent by doing division first. Please refer complete article on Program for cube sum of first n natural numbers for more details!


My Personal Notes arrow_drop_up
Last Updated : 22 May, 2023
Like Article
Save Article
Similar Reads