filmov
tv
Write a program to find the sum of squares of first n natural numbers.
![preview_player](https://i.ytimg.com/vi/isAOrUPI9Jw/maxresdefault.jpg)
Показать описание
#shorts #shortsvideo #shortsviral
here is a program
n = int(input("Enter a number: ")) # take input from user
# calculate the sum of squares using the formula
sum_of_squares = (n * (n + 1) * (2 * n + 1)) // 6
print("The sum of squares of first", n, "natural numbers is", sum_of_squares)
Let's understand how this program works:
We first take an integer n as input from the user using the input() function. Note that we use the int() function to convert the user input from a string to an integer.
We then use the mathematical formula to calculate the sum of squares of the first n natural numbers. The formula is:
sum_of_squares = n * (n + 1) * (2 * n + 1) // 6
Here, // is the integer division operator, which gives the floor of the division result. This formula is derived from the sum of squares formula:
1^2 + 2^2 + 3^2 + ... + n^2 = n * (n + 1) * (2n + 1) / 6
Once the calculation is done, we print out the result using the print() function. We use string concatenation to include the value of n and sum_of_squares in the output message.
Here's an example of how to use this program:
Enter a number: 5
The sum of squares of first 5 natural numbers is 55
In this example, the user has entered 5 as the value of n. The program calculates the sum of squares of the first 5 natural numbers (1, 2, 3, 4, and 5) and outputs the result as 55.
here is a program
n = int(input("Enter a number: ")) # take input from user
# calculate the sum of squares using the formula
sum_of_squares = (n * (n + 1) * (2 * n + 1)) // 6
print("The sum of squares of first", n, "natural numbers is", sum_of_squares)
Let's understand how this program works:
We first take an integer n as input from the user using the input() function. Note that we use the int() function to convert the user input from a string to an integer.
We then use the mathematical formula to calculate the sum of squares of the first n natural numbers. The formula is:
sum_of_squares = n * (n + 1) * (2 * n + 1) // 6
Here, // is the integer division operator, which gives the floor of the division result. This formula is derived from the sum of squares formula:
1^2 + 2^2 + 3^2 + ... + n^2 = n * (n + 1) * (2n + 1) / 6
Once the calculation is done, we print out the result using the print() function. We use string concatenation to include the value of n and sum_of_squares in the output message.
Here's an example of how to use this program:
Enter a number: 5
The sum of squares of first 5 natural numbers is 55
In this example, the user has entered 5 as the value of n. The program calculates the sum of squares of the first 5 natural numbers (1, 2, 3, 4, and 5) and outputs the result as 55.