nth level differences I have a sequence of numbers, I am calculating the difference between the numbers until I am left with a single integer.
2     1     3     4     3
   1    -2    -1     1    | level 1 differences
      3    -1    -2       | level 2 differences
         4     1          | level 3 differences
            5             | level 4 differences

I aim to get:

*

*number of levels

*final single integer difference

I am looking for a better way to approach this, since my list has thousands of numbers, thus, has a lot of levels.
Is there a better mathematical approach to this, rather than using the old school way for quadratic or cubic sequences?
 A: If you calculate the differences for a few iterations on a generic sequence, you get
$$\begin{array}{cccccccccc}
a_0&&a_1&&a_2&&a_3\\
&a_1 - a_0&&a_2 - a_1&&a_3 - a_2\\
&&a_2 - 2a_1 + a_0&&a_3 - 2a_2 + a_1\\
&&&a_3 - 3a_2 + 3a_1 - a_0
\end{array}$$
You might be able to spot the pattern forming here. In general $$f(a_0,\dots,a_n) = \sum_{k=0}^n (-1)^{n-k}\binom nka_k$$
Where $f$ is your final single difference.
The binomial coefficients have this property:
$$\binom n0 = 1, \binom nk = \frac{n - k+1}k\binom n{k-1}$$
which allows you to easily calculate the correct coefficient for each term as you go along. Note that despite the divisions, the binomial coefficient is always an integer.
Assuming you are using a 0-based array, this makes a convenient algorithm:
function Difference(array[]) 
{
    n = length(array) - 1
    coef = 1
    if(n is odd) coef = -1
    k = 0      //regardless of the type of your values, n, coef, k should all be integers
    d = 0      //d is of the same type as your values
    while(k <= n)
    {       
        d = d + coef * array[k]
        k = k + 1
        coef = -(n - k + 1) * coef / k
    }
    return d
}

