The possible original indices of the last remaining element are exactly through . Output the maximum in this range.
Compute this maximum while reading the sequence, using time and additional space.
Proof
Let be the product of all values of chosen so far, initially . The remaining elements always have original indices
Keeping every -th element leaves exactly the multiples of , preserving this property.
Exactly one element remains when , or equivalently,
Conversely, any index in this range can be left alone by choosing in the first operation. If , no operation is needed.
Thus, precisely the elements in the stated range can remain last.