Javatpoint Logo
Javatpoint Logo

Python Program for Calculating the Sum of Squares of First n Natural Numbers

In this tutorial, we will learn how to calculate the sum of squares of first n natural numbers using Python.

We have a positive integer "N", and our task is to calculate (12 + 22 + 32 + 42 + 52 +… + N2)

Example:

Method 1: O(N)

In this method, a user has to run the loop from 1 to "N" natural number, and for each K, 1 <= K <= N. The user has to find the K2 to calculate the sum.

Example:

Output:

Please enter the 'N' natural number:  56
60116

Method 2: O(1)

In this method, the user can calculate the sum of the square of the first "N" natural numbers by using the following formula:

For Example:

Code:

Output:

Please enter the 'N' natural number:  87
223300

How to Avoid Early Overflow:

For the large "NN" natural number, the value of [(NN * (NN + 1) * (2 * NN + 1)) / 6] would probably overflow. The users can avoid this situation by using the fact that (NN * (NN + 1)) must be divisible by 2.

Example:

Output:

Please enter the 'N' natural number:  567
121844520

Conclusion

In this tutorial, we have explained two methods for calculating the sum of squares of "N" natural numbers using python and avoiding the code's overflow.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA