The characteristic equation turns a linear recurrence into two numbers, its roots, and the initial conditions fix the two multipliers. Your program solves recurrences with two different whole-number roots and checks the formula at n = 10.
What to build
A program that finds the closed form a(n) = alpha r1^n + beta r2^n of a recurrence.
Requirements
- Read c1, c2, a(0) and a(1). The recurrence is a(n) = c1 a(n − 1) + c2 a(n − 2), and it is guaranteed to have two different whole-number roots.
- Print
roots: r1 r2with r1 < r2. - Print
alpha:andbeta:as exact values: a whole number such as-1, or a fraction in lowest terms such as2/3. - Print
a(10):and the value of the closed form at n = 10 (a whole number).
Input
One line with c1, c2, a0 and a1.
Output
Four lines.
Constraints
The roots are whole numbers between -10 and 10.
Example
Input:
5 -6 1 4
Output:
roots: 2 3
alpha: -1
beta: 2
a(10): 117074
Why it works
Trying a(n) = r^n turns the recurrence into r² = c1 r + c2, and with two different roots every solution is α r1^n + β r2^n. Matching a(0) = α + β and a(1) = α r1 + β r2 gives two equations in two unknowns, which have exactly one solution because the roots are different.
Examples
5 -6 1 4
roots: 2 3 alpha: -1 beta: 2 a(10): 117074
3 -2 1 3
roots: 1 2 alpha: -1 beta: 2 a(10): 2047
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
The roots of r**2 = c1*r + c2 are (c1 - s)/2 and (c1 + s)/2 where s = sqrt(c1*c1 + 4*c2); use math.isqrt.
Hint 2
With roots r1 and r2: beta = (a1 - r1*a0) / (r2 - r1), and alpha = a0 - beta.
Hint 3
Use fractions.Fraction for alpha and beta; print an integer without the denominator.
Solution
Show one correct solution (try it yourself first)
from fractions import Fraction
from math import isqrt
c1, c2, a0, a1 = map(int, input().split())
s = isqrt(c1 * c1 + 4 * c2)
r1, r2 = sorted([(c1 - s) // 2, (c1 + s) // 2])
beta = Fraction(a1 - r1 * a0, r2 - r1)
alpha = a0 - beta
print("roots:", r1, r2)
print("alpha:", alpha)
print("beta:", beta)
print("a(10):", alpha * r1 ** 10 + beta * r2 ** 10)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step