Sum square difference
Ebubechukwu O.
Founder and Technology at Tutlee | AI/ML Enthusiast | Passionate About Technical Education & Sustainable Impact
Coding Challenge Level: Beginner
Today's challenge requires you to write code to find the sum of the squares of the first ten natural numbers is,
12?+ 22?+ ... + 102?= 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2?= 552?= 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 ? 385 = 2640.
Find the difference between the sum of the squares of the first?n?natural numbers and the square of the sum.
Solution:
The formula to find the difference between the sum of squares and the square of the sum of the first n natural numbers is:
(square of the sum) - (sum of the squares)
To calculate this difference, we first need to calculate the sum of the first n natural numbers and the sum of the squares of the first n natural numbers. We can use loops and mathematical formulas to do this.
Here's the Python code:
领英推荐
def sum_square_difference(n):
? ? sum_of_n = (n * (n+1)) // 2? # formula for the sum of first n natural numbers
? ? sum_of_squares = (n * (n+1) * (2*n+1)) // 6? # formula for the sum of squares of first n natural numbers
? ? square_of_sum = sum_of_n ** 2
? ? return square_of_sum - sum_of_squares
The sum_square_difference function takes in a value of n and calculates the sum of the first n natural numbers and the sum of the squares of the first n natural numbers using the formulas above. Then it calculates the square of the sum of the first n natural numbers by squaring the sum of n. Finally, it returns the difference between the square of the sum and the sum of squares.
To use this function, simply call sum_square_difference and pass in the value of n as the argument. For example, to find the difference between the sum of the squares and the square of the sum of the first 10 natural numbers, you would call the function like this:
print(sum_square_difference(10))
This would output:
2640
So the difference between the sum of squares and the square of the sum of the first 10 natural numbers is 2640.
Similarly, to find the difference between the sum of squares and the square of the sum of the first 15 natural numbers, you would call the function like this:
print(sum_square_difference(15))
This would output:
13160
So the difference between the sum of squares and the square of the sum of the first 15 natural numbers is 13160.
In conclusion, if you ever need to find the difference between the sum of squares and the square of the sum of the first n natural numbers, the Python code above provides a simple and efficient solution using mathematical formulas.
Thank you for reading this far. To subscribe for more, click?here. Please share in the comment, how you would solve this challenge in your own way. You can include any programming language you are familiar with. Someone might benefit from you.