Write a Program That Takes a Number `N` as Input And Prints The Sum of The Squares of The First `N` Positive Integers

Hi, in this article let's learn a python program to accept an integer N from the user and find the sum of squares of first N positive numbers.

The formula to find the sum of squares of first N natural numbers is given as below

Total = [n(n + 1)(2n + 1)] / 6

Let’s try to find out the sum of squares of first N natural numbers using the loop basic method and in the second program let's use the above formula to find the sum of squares.

 

 

Write a Program That Takes a Number `N` as Input And Prints The Sum of The Squares of The First `N` Positive Integers

 

 

 


Write a Program That Takes a Number `N` as Input And Prints The Sum of The Squares of The First `N` Positive Integers

I will be using a basic method to find the sum of squares of numbers. Let's take an integer variable n and ask the user to enter the number using input function call. Then convert it into integer, take another variable named as total and set it to 0.

Use the for loop to iterate from 0 to n  and get the index values within this range and inside the for loop raise the index to power of 2 and add it to total. To raise any value to power of 2 you should be using double star operator in python as shown below. Finally print the total.

Complete Python Program
========================

n = int(input("Enter a Number : "))

total = 0
for index in range(n+1):
   total += index ** 2

print("Sum of squares of number is : ", total)




Now I will be using the formula to find the sum of squares of a number i.e,  [n(n + 1)(2n + 1)] / 6. After asking the user input i.e, an integer, use the formula directly, compute the sum of squares and store it in the total variable. Finally use the print() function call to print the total variable.

Complete Python Program
========================

n = int(input("Enter a Number : "))

total = (n * (n+1) * ((2 * n) + 1)) / 6
print("Sum of squares of number is : ", total)




Output 1
======================
Enter a Number : 1024
Sum of squares of number is :  358438400.0




Output 2
======================
Enter a Number : 55
Sum of squares of number is :  56980.0




Conclusion
===============================
There are two versions of the same program, try executing both the programs by providing the random integer values as input and note down the result.

Comment it down below if you have any suggestions regarding the above python program.



Post a Comment

0 Comments