# Python program for sum of square of first N natural numbers

Here, we will write a Python program to find the sum of square of first N natural numbers.
Submitted by Shivang Yadav, on April 03, 2021

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Sum of square of first N Natural Numbers

12 + 22 + 32 + 42 + ... N2

We will get the value of N as input from the user and then print the sum of squares of the first N natural numbers.

Example:

```Input:
N = 5

Output:
55
```

Method 1: Using Loop

A simple solution is to loop from 1 to N, and add their squares to sumVal.

Program to find the sum of the square of first N natural number

```# Python program for sum of the
# square of first N natural numbers

# Getting input from users
N = int(input("Enter value of N: "))

# calculating sum of square
sumVal = 0
for i in range(1, N+1):
sumVal += (i*i)

print("Sum of squares = ", sumVal)
```

Output:

```RUN 1:
Enter value of N: 10
Sum of squares =  385

RUN 2:
Enter value of N: 12
Sum of squares =  650
```

Explanation:

In the above code, we have taken input from the user for the value of N. And then we have initialized the sumVal to 0 and looping from 1 to N, we will add the value (i2) to the sumVal. At last, printed the sumVal.

Method 2: Using mathematical formula

A direct approach to find the sum of squares is using the mathematical formula.

The formula is,

sum = { (N * (N+1) * ((2*N) + 1))/6 }

Program for the sum of the squares of first N natural numbers

```# Python program for sum of the
# square of first N natural numbers

# Getting input from user
N = int(input("Enter value of N: "))

# calculating sum of square
sumVal =  (int)( (N * (N+1) * ((2*N) + 1))/6 )
print("Sum of squares =",sumVal)
```

Output:

```RUN 1:
Enter value of N: 10
Sum of squares =  385

RUN 2:
Enter value of N: 12
Sum of squares =  650
```

Explanation:

In the above code, we have taken input from the user for the value of N. And then we have used the formula to get the sum and store it to sumVal and print it.

Preparation

What's New

Top Interview Coding Problems/Challenges!