Find sum of consecutive triangular number recursively

351 Views Asked by At

In Computer Science, I was asked to write a program that finds the sum of (1 to n)th triangular number, where n is a positive integer.

  • If n=1, result is 1
  • If n=2, result is (1) + (1 + 2)

By testing values from 1 to 8, I found that T(n) = n2 + T(n-2) when n > 2.
T(n) is simply n2 when n=1 or 2.

But how does that work?

EDIT: I am sorry if I haven't clarified yet, but RECURSION is required.

3

There are 3 best solutions below

5
On BEST ANSWER

As you seem to have it, the triangular numbers are given by:

$$\triangle n=1+2+3+\dots+n$$

and the sum of triangular numbers:

$$T(n)=\triangle1+\triangle2+\triangle3+\dots+\triangle n$$

To verify your recurrence, we can consider differences by rearranging it as $T(n)-T(n-2)=n^2$ and substitute it in to get:

\begin{align}T(n)-T(n-2)&=\overbrace{\triangle1+\triangle2+\dots+\triangle(n-2)+\triangle(n-1)+\triangle n}^{T(n)}\\&-(\underbrace{\triangle1+\triangle2+\dots+\triangle(n-2)}_{T(n-2)})\\&=\triangle(n-1)+\triangle n\\&\stackrel?=n^2\end{align}

So we need to verify if we have:

$$\triangle(n-1)+\triangle n=n^2$$

This can be done once again by considering differences since it is clear that it holds for $n=1$, leaving us with:

$$\underbrace{\triangle(n-1)+\triangle n}_{n^2}-\underbrace{\triangle(n-2)-\triangle(n-1)}_{(n-1)^2}=n^2-(n-1)^2$$

These reduce down to:

\begin{align}\triangle n-\triangle(n-2)&=\overbrace{1+2+\dots+(n-2)+(n-1)+n}^{\triangle n}\\&-(\underbrace{1+2+\dots+(n-2)}_{\triangle(n-2)})\\&=(n-1)+n\\&=2n-1\\&=n^2-n^2+2n-1\\&=n^2-(n-1)^2\end{align}

which inductively verifies $\triangle(n-1)+\triangle n=n^2$, and hence $T(n)=T(n-2)+n^2$.


Note: It is likely the task wanted you to find a direct recurrence. There's a lot of work here to verify the recurrence, which is probably not expected. Often times you should simply try working it by hand. Then you may've realized that it's straightforward to compute it iteratively as follows:

function sum_of_triangles(n)
  sum = 0
  triangle = 0
  for k in 1..n
    triangle += k
    sum += triangle
  end
  return sum

Writing this "purely" with recursively defined functions is fairly messy though if one does not have the formula for $\triangle n$ at hand. If one did, then this can be worked out as

function sum_of_triangles(n)
  if n == 0
    return 0
  else
    return sum_of_triangles(n-1) + triangle(n) // triangle(n) = n*(n+1)/2
1
On

If $t(n)$ is the $n$-th triangular number and $T(n)$ is the sum of the first $n$ triangular numbers, $T(n)=\sum_{k=1}^n t(k)$, then $$ T(n) - T(n-2) = t(n)+t(n-1) = \frac12 n(n+1) + \frac12(n-1)(n) = \frac12 n(n+1+n-1) = n^2 $$

0
On

This is called Pascal's Triangle. The triangular numbers are the third diagonal (first is all ones). The cumulative sums are in the fourth diagonal.

Also see the answer by Yves at Triangular numbers and pascal's trangle

enter image description here