How to speed up series generation?

纵饮孤独 提交于 2019-11-30 03:25:45

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

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.

Just thinking here but take a look at Duff's device for the count_fair_coins function as that will automatically unroll the loop to speed up that function.

Precomputing the sqrt's in the generating function seems like the easiest way to get any speed up. Which would reduce to just a single pow call and multiplication of constants. As well as precomuting the sqrt's another way to speed it up is to remove the divisions and use the inverse multiplication, although a very slight optimization it might help speed up when n is very large.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!