|
1 |
| -# DarkCoder |
2 |
| -def sum_of_series(first_term: int, common_diff: int, num_of_terms: int) -> float: |
| 1 | +#Reeka |
| 2 | +def sum_of_ap_series(a: int, d: int, n: int) -> int: |
3 | 3 | """
|
4 |
| - Find the sum of n terms in an arithmetic progression. |
| 4 | + Calculates the sum of the first 'n' terms of an arithmetic progression (AP) |
| 5 | + series with the first term 'a' and common difference 'd'. |
| 6 | + |
| 7 | + Parameters: |
| 8 | + a (int): The first term of the AP. |
| 9 | + d (int): The common difference between terms. |
| 10 | + n (int): The number of terms to sum. |
5 | 11 |
|
6 |
| - >>> sum_of_series(1, 1, 10) |
7 |
| - 55.0 |
8 |
| - >>> sum_of_series(1, 10, 100) |
9 |
| - 49600.0 |
10 |
| - """ |
11 |
| - total = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) |
12 |
| - # formula for sum of series |
13 |
| - return total |
14 |
| - |
15 |
| - |
16 |
| -def main(): |
17 |
| - print(sum_of_series(1, 1, 10)) |
| 12 | + Returns: |
| 13 | + int: The sum of the first 'n' terms of the AP. |
18 | 14 |
|
19 |
| - |
20 |
| -if __name__ == "__main__": |
21 |
| - import doctest |
22 |
| - |
23 |
| - doctest.testmod() |
| 15 | + Examples: |
| 16 | + >>> sum_of_ap_series(1, 1, 5) # Sum of first 5 natural numbers |
| 17 | + 15 |
| 18 | + >>> sum_of_ap_series(2, 3, 4) # Sum of 2, 5, 8, 11 |
| 19 | + 26 |
| 20 | + >>> sum_of_ap_series(5, 0, 3) # Sum of 5, 5, 5 |
| 21 | + 15 |
| 22 | + >>> sum_of_ap_series(1, 2, 1) # Single term AP series |
| 23 | + 1 |
| 24 | + >>> sum_of_ap_series(1, -1, 5) # Decreasing AP series |
| 25 | + -5 |
| 26 | + >>> sum_of_ap_series(1, 1, -5) # Negative 'n' should raise an error |
| 27 | + Traceback (most recent call last): |
| 28 | + ... |
| 29 | + ValueError: Number of terms 'n' must be a positive integer |
| 30 | + >>> sum_of_ap_series(1, 1, 0) # Zero terms should also raise an error |
| 31 | + Traceback (most recent call last): |
| 32 | + ... |
| 33 | + ValueError: Number of terms 'n' must be a positive integer |
| 34 | + """ |
| 35 | + if n <= 0: |
| 36 | + raise ValueError("Number of terms 'n' must be a positive integer") |
| 37 | + |
| 38 | + # Formula for the sum of an AP series: S_n = n/2 * (2a + (n-1) * d) |
| 39 | + return n * (2 * a + (n - 1) * d) // 2 |
| 40 | +#Reeka |
0 commit comments