From 37c0953597d3e6f3e077a7d12bb7d0e3d1c2c7ec Mon Sep 17 00:00:00 2001 From: Byte Bender <136265142+BYT-Bender@users.noreply.github.com> Date: Thu, 10 Oct 2024 10:13:36 +0530 Subject: [PATCH] Create sum_of_squares.py --- maths/sum_of_squares.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 maths/sum_of_squares.py diff --git a/maths/sum_of_squares.py b/maths/sum_of_squares.py new file mode 100644 index 000000000..1af5d0b8b --- /dev/null +++ b/maths/sum_of_squares.py @@ -0,0 +1,31 @@ +""" +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. +""" + +def sum_of_squares(n: int) -> int: + """ + Implements the sum of squares formula for 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()