Python Program for Sum of Squares of first n natural numbers
Hello coders, in this tutorial we are going to discuss and write the code for the sum of squares of first n natural numbers using Python. Firstly, we will see the proof then we will proceed with the coding part.
Sum of the square of first n natural number using Python
Given a positive integer n., The task is to find 12 + 22 + 32 + ….. + n2
Now let’s see our program to perform the task.
Input : n = 5 Output : 30 1 + 4 + 9 + 16 +25= 55 Input : n = 6 Output : 91
#Using Method 1 def squaresum(n) : s = 0 #Iteration from 1 to n for i in range(1, n+1) : s = s + (i * i) return s n = 5 print(squaresum(n))
Using the formula
Sum of square of first n natural numbers = (n*(n+1)*(2*n+1))/6
Code for technique 2:-
#Using Method 2 def squaresum(n) : return (n * (n + 1) * (2 * n + 1)) // 6 n = 4 print(squaresum(n))