Python Program for sum of squares of n natural numbers

In this article, we will learn to find the sum of the square of the first n number using the python program.

We find the sum of the square of positive numbers from 1 to nth using two methods:

  • using for loop
  • using mathematical formula

the sum of the square of n numbers:

12 + 22 + 32 + 42 + ....... + (n-1)2 + n2




Method 1: Using for loop

Time Complexity for this program is: O(N)

Program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Sum of the square of positive numbers from 1 to nth using forloop
n = int(input("Enter nth number: "))
sum = 0

for i in range(1,n+1):
    sum = sum + (i*i)

print("Sum of the square of the number from 1 to",n,"is: ",sum)

# Sum of the square of positive numbers from of nth using forloop - docodehere.com

Output

Enter nth number: 10
Sum of the square of the number from 1 to 10 is:  385



Method 2: Using Mathematical formula

Time Complexity for this program is: O(1)

Program

1
2
3
4
5
6
# Sum of the square of positive numbers from 1 to nth without forloop
n = int(input("Enter nth number: "))

print((n * (n + 1) / 2) * (2 * n + 1) / 3)

# Sum of the square of positive numbers from of nth without forloop - docodehere.com

Output

Enter nth number: 2
5
Next Post Previous Post
No Comment
Add Comment
comment url