For your recursive relationship, you also need a base register.
T(1) = c T(n) = T(n-1) + n
To solve this problem, you can first guess the solution and then prove that it works using induction.
T(n) = (n + 1) * n / 2 + c - 1
Base register first. When n = 1, this gives c as required.
For other n:
T(n) = (n + 1) * n / 2 + c - 1 = ((n - 1) + 2) * n / 2 + c - 1 = ((n - 1) * n / 2) + (2 * n / 2) + c - 1 = (n * (n - 1) / 2) + c - 1) + (2 * n / 2) = T(n - 1) + n
So the solution works.
To get the guess first, note that your recurrence relation generates triangular numbers when c = 1:
T(1) = 1: * T(2) = 3: * ** T(3) = 6: * ** *** T(4) = 10: * ** *** **** etc..
Intuitively, a triangle is about half a square, and constants can be ignored in a Big-O record, so O (n ^ 2) is the expected result.
Mark byers
source share