mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Merge 7800f1e645
into f3f32ae3ca
This commit is contained in:
commit
c3aa695f1c
|
@ -1,23 +1,42 @@
|
||||||
# DarkCoder
|
# Reeka
|
||||||
def sum_of_series(first_term: int, common_diff: int, num_of_terms: int) -> float:
|
def sum_of_ap_series(a: int, d: int, n: int) -> int:
|
||||||
"""
|
"""
|
||||||
Find the sum of n terms in an arithmetic progression.
|
Calculates the sum of the first 'n' terms of an arithmetic progression (AP)
|
||||||
|
series with the first term 'a' and common difference 'd'.
|
||||||
|
|
||||||
>>> sum_of_series(1, 1, 10)
|
Parameters:
|
||||||
55.0
|
a (int): The first term of the AP.
|
||||||
>>> sum_of_series(1, 10, 100)
|
d (int): The common difference between terms.
|
||||||
49600.0
|
n (int): The number of terms to sum.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
int: The sum of the first 'n' terms of the AP.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
>>> sum_of_ap_series(1, 1, 5) # Sum of first 5 natural numbers
|
||||||
|
15
|
||||||
|
>>> sum_of_ap_series(2, 3, 4) # Sum of 2, 5, 8, 11
|
||||||
|
26
|
||||||
|
>>> sum_of_ap_series(5, 0, 3) # Sum of 5, 5, 5
|
||||||
|
15
|
||||||
|
>>> sum_of_ap_series(1, 2, 1) # Single term AP series
|
||||||
|
1
|
||||||
|
>>> sum_of_ap_series(1, -1, 5) # Decreasing AP series
|
||||||
|
-5
|
||||||
|
>>> sum_of_ap_series(1, 1, -5) # Negative 'n' should raise an error
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValueError: Number of terms 'n' must be a positive integer
|
||||||
|
>>> sum_of_ap_series(1, 1, 0) # Zero terms should also raise an error
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValueError: Number of terms 'n' must be a positive integer
|
||||||
"""
|
"""
|
||||||
total = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff)
|
if n <= 0:
|
||||||
# formula for sum of series
|
raise ValueError("Number of terms 'n' must be a positive integer")
|
||||||
return total
|
|
||||||
|
# Formula for the sum of an AP series: S_n = n/2 * (2a + (n-1) * d)
|
||||||
|
return n * (2 * a + (n - 1) * d) // 2
|
||||||
|
|
||||||
|
|
||||||
def main():
|
# Reeka
|
||||||
print(sum_of_series(1, 1, 10))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
import doctest
|
|
||||||
|
|
||||||
doctest.testmod()
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user