To get this sequence I just made up, which will subsequently be referred to as TSIJMU, consider the harmonic series:
\$ \frac{1}{2} + \frac{1}{3} + \frac{1}{4} ...\$
But what if you only add a term if it doesn't make the sum so far over 1, and otherwise subtract? Let's see an example here, starting at \$\frac{1}{2}\$:
Sum so far: 0, term: \$ \frac{1}{2} \$
\$ 0 + \frac{1}{2} = \frac{1}{2}\$, which is less than 1,so we add.
Sum so far: \$ \frac{1}{2} \$, term: \$ \frac{1}{3} \$
\$ \frac{1}{3} + \frac{1}{2} = \frac{5}{6}\$, which is less than 1,so we add.
Sum so far: \$ \frac{5}{6} \$, term: \$ \frac{1}{4} \$
\$ \frac{1}{4} + \frac{5}{6} = \frac{13}{12}\$, which is more than 1,so we subtract, yielding \$\frac{7}{12}\$.
If you do this forever, TSIJMU is the sequence of integers that are added when doing this. This goes 2,3,5,6,8, etc.
Rules
Your code must not fail due to floating point errors. As pointed out by Arnauld, this means your code may fail due to integer overflow errors. If this is the case, please provide a version which works for arbitrary input size.
As with all sequence challenges, there are three ways you can output:
- Take a number \$n\$ and return the nth item of TSIJMU
- Take a number \$n\$ and return the first n items of TSIJMU
- Print TSIJMU infinitely.
Scoring
This is code-golf, shortest wins!
Testcases
These are 0-indexed, but you can take 1-indexed.
0 => 2
3 => 6
9 => 17
25 => 48
58 => 113
90 => 177
156 => 308
352 => 700
479 => 953
As requested by Bubbler, the first 20 terms are:
2,3,5,6,8,10,12,13,15,17,19,21,23,25,27,29,31,33,34,36