Skip to content

Commit 7f8f583

Browse files
committed
feat(day 9): add sumOfSquares function with optimal mathematical formula
1 parent bfafc57 commit 7f8f583

2 files changed

Lines changed: 51 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""
2+
================================================================> Sum of Squares <====================================================================================
3+
Given a positive integer up to 1,000, return the sum of all the integers squared from 1 up to the number.
4+
5+
==========================================================================================================================================================================================
6+
O/P : ====>
7+
8+
1. sum_of_squares(5) should return 55.
9+
2. sum_of_squares(10) should return 385.
10+
3. sum_of_squares(25) should return 5525.
11+
12+
"""
13+
14+
def sum_of_squares(n):
15+
return sum(num**2 for num in range(1,n+1))
16+
17+
18+
# Bonus : Which is a Mathematical Formula
19+
# If we optimize the code further, the sum of squares from 1 to n can be computed directly:
20+
# sum = n(n+1)(2n + 1) // 6
21+
22+
def sum_of_squares_optimal(n):
23+
return n * (n + 1) * (2 * n + 1) // 6
24+
# This avoids iteration entirely and is lighting -fast especially usefull if n gets very large.
25+
26+
27+
if __name__ == "__main__":
28+
print(sum_of_squares(5))
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import unittest
2+
from sumOfSquares import sum_of_squares
3+
4+
class sumOfSquares(unittest.TestCase):
5+
6+
def test1(self):
7+
self.assertEqual(sum_of_squares(5),55)
8+
9+
def test2(self):
10+
self.assertEqual(sum_of_squares(10),385)
11+
12+
def test3(self):
13+
self.assertEqual(sum_of_squares(25),5525)
14+
15+
def test4(self):
16+
self.assertEqual(sum_of_squares(500),41791750)
17+
18+
def test5(self):
19+
self.assertEqual(sum_of_squares(1000),333833500)
20+
21+
22+
if __name__ == "__main__":
23+
unittest.main()

0 commit comments

Comments
 (0)