Пайтон. Дано арифметичну прогресію, перший член якої дорівнює а, та знаменник d. Розробіть програму рекурсивного обчислення n-го члена прогресії. Уведіть і виконайте програму для різних значень початкових даних.
Ответы
Here is a Python program that calculates the nth term of an arithmetic progression given the first term and the common difference:
def nth_term(a, d, n):
if n == 1:
return a
else:
return nth_term(a, d, n-1) + d
# Test the function with different initial data
print(nth_term(1, 2, 1)) # Output: 1
print(nth_term(1, 2, 2)) # Output: 3
print(nth_term(1, 2, 3)) # Output: 5
print(nth_term(1, 2, 4)) # Output: 7
The function nth_term takes in three arguments: a, the first term of the arithmetic progression; d, the common difference; and n, the position of the term being calculated. The function uses recursion to calculate the nth term by calling itself with n-1 as the argument for n until n is equal to 1, at which point it returns the first term of the progression. The common difference is added to the result of the recursive call at each step.