- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program for cube sum of first n natural numbers
In this article, we will learn about the solution and approach to solve the given problem statement.
Problem statement −Given an input n, we need to print the sum of series 13 + 23 + 33 + 43 + …….+ n3 till n-th term.
Here we will discuss two approach to reach the solution of the problem statement −
- Brute-force approach using loops.
- Mathematical solution of sum of n numbers.
Approach 1 −Computing sum of each term by adding by iterating over the numbers
Example
def sumOfSeries(n): sum = 0 for i in range(1, n+1): sum +=i*i*i return sum # Driver Function n = 3 print(sumOfSeries(n))
Output
36
Approach 2 −Computation using mathematical formula
Here we will be using mathematical sum formulae which is aldready derived for the cubic sum of natural numbers.
Sum = ( n * (n + 1) / 2 ) ** 2
Example
def sumOfSeries(n): x = (n * (n + 1) / 2) return (int)(x * x) # main n = 3 print(sumOfSeries(n))
Output
36
Conclusion
In this article, we learned about the approach to compute the cube sum of first n natural numbers.
Advertisements