This solution takes advantage of the fact that fg is linear in terms of add and sub. The main loop consists of repeated application of fg and subtraction of n. Reordering this expression results in a subtraction between a power of fg applied to x and the sum of powers of fg applied to k successive values. Powers of fg can be computed quickly as fg^64 = id and the sum of powers of fg applied to successive values happens to show a pattern every 192 terms.