How to speed up series generation?

后端 未结 2 1368
我寻月下人不归
我寻月下人不归 2020-12-28 18:28

The problem requires to generate the n-th element of a sequence that is similar to Fibonacci sequence. However, it\'s a bit tricky because n is ver

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-28 19:29

    You can write the terms of the sequence in terms of matrix exponentials:

    enter image description here

    which can be quickly evaluated using exponentiation by squaring. This leads to an O(log n) solution which should solve the problem well within the time constraints.

    Just for future reference, if you are required to do multiplication with large numbers (not applicable in this situation since the answer is taken modulo 1000000007), you should look into the Karatsuba algorithm. This gives you sub-quadratic time multiplication.

提交回复
热议问题