
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program for cube sum of first n natural numbers in C++
In this article, We implement a C++ program to print sum of series like 13 + 23 + 33 + 43 + .......+ n3 till the nth term.
Given an integer n, calculate the sum of the cubes of the first n natural integers. So, we have to cube of 'n' natural integers and sum the results.
Example Scenario
Let's understand the following example scenario:
Input: n = 4 Output: 100 Explanation: 13 + 23 + 23 + 43
Another example scenario:
Input: n = 5 Output: 225 Explanation: 13 + 23 + 23 + 43 + 43
Cube Sum of First N Natural Numbers Using Naive Approach
A naive approach is a simple solution to a problem that does not take any advantage of special property or optimization.
We will be using the simple iterative approach in which we can use any loops. Let's see the below steps to solve the problem:
- Define the function "sum_of_series" which takes integer input n.
- Declare a variable sum. initialize it with 0.
- Start a loop with 'i' ranging from 1 to 'n': For each iteration of the loop, Keep adding all the cubes to a sum variable.
- When the loop ends, return the sum.
Example
In the following example, we compute the cube sum of the first n natural number using the naive approach or iterative:
#include <iostream> using namespace std; //function to calculate the sum of series int sum_of_series(int n){ int sum = 0; for (int i = 1; i <= n; i++) sum += i * i * i; return sum; } int main(){ int n = 5; cout<<"sum of series is : "<<sum_of_series(5); return 0; }
Following is the output:
sum of series is : 225
The above approach takes O(n) time and O(1) space complexity.
Cube Sum of First N Natural Numbers Using Mathematical Formula
It is an efficient solution to compute the cube sum of the first n natural number using this formula: (n ( n + 1 ) / 2) ^ 2.
Let's see how does this formula work:
For input: n = 4; =(4(4+1)/2)2 =(4*5/2)2 =(20/2)2 =(10)2 =100
Example
In the following example, we compute the cube sum of the first n natural number using mathematical formula:
#include <iostream> using namespace std; int sum_of_series(int n) { int sum = (n * (n + 1) / 2); return sum * sum; } int main() { int n = 4; cout<<"sum of series is : " << sum_of_series(n); return 0; }
Following is the output of the code:
sum of series is : 100
The above approach takes O(1) time and O(1) space complexity.