Print the sum of series 13 + 23 + 33 + 43 + …….+ n3 till n-th term.
Input : n = 5 Output : 225 13 + 23 + 33 + 43 + 53 = 225 Input : n = 7 Output : 784 13 + 23 + 33 + 43 + 53 + 63 + 73 = 784
Time Complexity : O(n)
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
Time Complexity : O(1)
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!
- Program for cube sum of first n natural numbers
- C Program for cube sum of first n natural numbers
- C++ Program for cube sum of first n natural numbers
- Java Program for cube sum of first n natural numbers
- Python Program for Sum of squares of first n natural numbers
- Sum of cubes of first n odd natural numbers
- Sum of alternating sign cubes of first N Natural numbers
- Average of Cubes of first N natural numbers
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Minimum value of K such that sum of cubes of first K natural number is greater than equal to N
- Cube Free Numbers smaller than n
- Count numbers upto N which are both perfect square and perfect cube
- Print N numbers such that their product is a Perfect Cube
- Program for Volume and Surface Area of Cube
- C Program to check whether a number is a Perfect Cube or not
- Count all triplets whose sum is equal to a perfect cube
- Construct an Array of size N whose sum of cube of all elements is a perfect square
- Construct an Array such that cube sum of all element is a perfect square
- Sum of cubes of even and odd natural numbers
- Find Cube Pairs | Set 1 (A n^(2/3) Solution)