Skip to content

Add Sum of Squares Algorithm #11929

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions maths/sum_of_squares.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""
This script demonstrates the implementation of the
sum of squares of the first n natural numbers.

The function takes an integer n as input and returns the sum of squares
from 1 to n using the formula n(n + 1)(2n + 1) / 6.

This formula computes the sum efficiently
without the need for iteration.

https://www.cuemath.com/algebra/sum-of-squares/
"""


def sum_of_squares(n: int) -> int:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: n

"""
Implements the sum of squares formulafor the first n natural numbers.

Parameters:
n (int): A positive integer representing the limit of the series

Returns:
sum_squares (int): The sum of squares of the first n natural numbers.

Examples:
>>> sum_of_squares(5)
55

>>> sum_of_squares(10)
385
"""
return n * (n + 1) * (2 * n + 1) // 6


if __name__ == "__main__":
import doctest

doctest.testmod()