Extrapolation Using a Difference Table
InterviewTime limit1sMemory limit128 MB
Extend a sequence by k steps using a polynomial difference table, always assuming the highest-order differences stay constant, and print the (n+k)-th term.
- Level
Medium5 of 10
- Topics
- Math, Dynamic programming, Combinatorics, Implementation
- Solved
- No attempts yet
Problem
A very old technique for extrapolating a sequence of values relies on a difference table. For example, the difference table for the four values can be displayed like this.

The original sequence appears in the first column. Each entry in the second column is the difference between adjacent entries in the first column; these are the first differences. Each entry in the third column is the difference between adjacent entries in the second column (the second differences), and so on. The last column always holds exactly one value. If the sequence has values, the completed table has columns, and the single value in column is the -th difference.
To extrapolate, we assume the -th differences are constant (nothing in the data suggests otherwise). Under that assumption we compute the next entry in the -th difference column, then the -th column, and so on, until we reach the next entry of the first column — the next value of the sequence. The table below adds four entries (boxed) to extend the example, producing the next value . The process can continue as far as we like, always assuming the -th differences stay constant.

Input
The input is a series of extrapolation requests. Each request begins with an integer , the number of values in the sequence to be extended. When is , the program terminates. Otherwise is at most and is followed by integers, the given elements of the sequence. Each request ends with (at least ), the number of extrapolation steps to perform: you add entries to each column of the difference table. Number the given values through .
Tokens may be separated by any amount of whitespace.
Output
For each request, extrapolate the original sequence times and report the -th value. Print exactly one line per request in the form Term X of the sequence is Y, where X is and Y is the extrapolated value.
Hint: has no stated upper bound, so you may not be able to hold the entire difference table in memory.