This page is still under construction.

Parts of this page are still being built. What you see may change.

Extrapolation Using a Difference Table

Interview

Time limit1sMemory limit128 MB

Summary
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 3,6,10,153, 6, 10, 15 can be displayed like this.

Difference table for 3, 6, 10, 15

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 nn values, the completed table has nn columns, and the single value in column nn is the (n−1)(n-1)-th difference.

To extrapolate, we assume the (n−1)(n-1)-th differences are constant (nothing in the data suggests otherwise). Under that assumption we compute the next entry in the (n−2)(n-2)-th difference column, then the (n−3)(n-3)-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 2121. The process can continue as far as we like, always assuming the (n−1)(n-1)-th differences stay constant.

Extending the difference table to get 21

Input

The input is a series of extrapolation requests. Each request begins with an integer nn, the number of values in the sequence to be extended. When nn is 00, the program terminates. Otherwise nn is at most 1010 and is followed by nn integers, the given elements of the sequence. Each request ends with kk (at least 11), the number of extrapolation steps to perform: you add kk entries to each column of the difference table. Number the given values 11 through nn.

Tokens may be separated by any amount of whitespace.

Output

For each request, extrapolate the original sequence kk times and report the (n+k)(n+k)-th value. Print exactly one line per request in the form Term X of the sequence is Y, where X is n+kn+k and Y is the extrapolated value.

Hint: kk has no stated upper bound, so you may not be able to hold the entire difference table in memory.

Examples1

  1. Example 1

    Input
    4  3  6  10  15  1
    4  3  6  10  15  2
    3  2  4  6  20
    6  3  9  12  5  18  -4  10
    0
    
    Expected output
    Term 5 of the sequence is 21
    Term 6 of the sequence is 28
    Term 23 of the sequence is 46
    Term 16 of the sequence is -319268