Skip to content

Commit 6c2c08c

Browse files
AxSmasher44cclauss
andauthored
sum_of_geometric_progression (TheAlgorithms#2168)
* Add files via upload * Rename sum_of_Geometric_Progression.py to sum_of_geometric_progression.py * Update sum_of_geometric_progression.py * Update maths/sum_of_geometric_progression.py Co-authored-by: Christian Clauss <cclauss@me.com> * Update maths/sum_of_geometric_progression.py Co-authored-by: Christian Clauss <cclauss@me.com> * Update maths/sum_of_geometric_progression.py Co-authored-by: Christian Clauss <cclauss@me.com> * Update sum_of_geometric_progression.py * Update sum_of_geometric_progression.py * Type hints and test for zeros and negative numbers * Update sum_of_geometric_progression.py Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 05c14c6 commit 6c2c08c

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

maths/sum_of_geometric_progression.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
def sum_of_geometric_progression(
2+
first_term: int, common_ratio: int, num_of_terms: int
3+
) -> float:
4+
""""
5+
Return the sum of n terms in a geometric progression.
6+
>>> sum_of_geometric_progression(1, 2, 10)
7+
1023.0
8+
>>> sum_of_geometric_progression(1, 10, 5)
9+
11111.0
10+
>>> sum_of_geometric_progression(0, 2, 10)
11+
0.0
12+
>>> sum_of_geometric_progression(1, 0, 10)
13+
1.0
14+
>>> sum_of_geometric_progression(1, 2, 0)
15+
-0.0
16+
>>> sum_of_geometric_progression(-1, 2, 10)
17+
-1023.0
18+
>>> sum_of_geometric_progression(1, -2, 10)
19+
-341.0
20+
>>> sum_of_geometric_progression(1, 2, -10)
21+
-0.9990234375
22+
"""
23+
if common_ratio == 1:
24+
# Formula for sum if common ratio is 1
25+
return num_of_terms * first_term
26+
27+
# Formula for finding sum of n terms of a GeometricProgression
28+
return (first_term / (1 - common_ratio)) * (1 - common_ratio ** num_of_terms)

0 commit comments

Comments
 (0)