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

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.


原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263279.html

(0)
上一篇 2022年5月30日
下一篇 2022年5月30日

相关推荐

发表回复

登录后才能评论