What's the general formula for the sum total of first k terms of the following?

157 Views Asked by At

I have written a naive code to calculate the sum total of the first k terms of a sequence. It's too complicated for me to write it here in "mathematical" language with nested summations and all.

Code:

int foobar(int n, int k)
{
    if (k == 1)
        return n-1;
    
    int count = 0;
    for (int i = 1; i <= n-k; ++i)
        count = count + foobar(n-i, k-1);
    return count;
}

Does there exist a general formula for the sum of the first k terms in terms of n and k?

Edit: The formula for the function: $f(n,k)=\begin{cases}n-1,&\hbox{ for }k=1\\ \sum\limits_{i=1}^{n-k}f(n-i,k-1),&\hbox{ for }k\ne1\end{cases}$

1

There are 1 best solutions below

0
On BEST ANSWER

$f(n,k)=\frac{(n-1)...(n-k)}{k!}= $${n-1}\choose{k}$

Edit: this holds because pascal's equality holds, indeed

$f(n,k)=f(n-1,k-1)+(f(n-2,k-1)+...+f(k,k-1))=f(n-1,k-1)+f(n-1,k)$