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)
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.
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:
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.
Please enter the 'N' natural number: 567 121844520
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.
JavaTpoint offers too many high quality services. Mail us on [email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected]
Duration: 1 week to 2 week