problem 539 // project euler



Odd elimination

Start from an ordered list of all integers from 1 to n. Going from left to right, remove the first number and every other number afterward until the end of the list. Repeat the procedure from right to left, removing the right most number and every other number from the numbers left. Continue removing every other numbers, alternating left to right and right to left, until a single number remains.

Starting with n = 9, we have:
1 2 3 4 5 6 7 8 9
2 4 6 8 2 6
6

Let P(n) be the last number left starting with a list of length n.
Let $displaystyle S(n) = sum_{k=1}^n P(k)$
You are given P(1)=1, P(9) = 6, P(1000)=510, S(1000)=268271.

Find S(1018) mod 987654321.


奇数位消除

从1至n组成的有序数列开始,从左往右,消除所有奇数位上的数;然后重复这一过程,直到只剩下一个数。

初始时若n = 9,我们有:
1 2 3 4 5 6 7 8 9
2 4 6 8
2 6
6

记P(n)为初始数列长度为n时最后剩下的数字。
令$displaystyle S(n) = sum_{k=1}^n P(k)$
已知P(1)=1,P(9) = 6,P(1000)=510,S(1000)=268271。

求S(1018) mod 987654321。