This is more complicated than I thought, but I think I found a solution for the simplest case (k = 2).
At first I tried to simplify by asking the following question: what position in the sequence has numbers 10^i * k where i = 1, 2, 3, ... ? For k = 2, the numbers 20, 200, 2000, ...
ikn 1 2 20/2 = 10 2 2 200/2 + 2* 5 = 110 3 2 2000/2 + 2* 50 + 18* 5 = 1190 4 2 20000/2 + 2*500 + 18*50 + 162*5 = 12710 i 2 10^i + 2*10^(i-1)/2 + 18*10^(i-2)/2 + 162*10^(i-3)/2 + ?*10^(i-4)/2 + ...
In the last line, I tried to express the pattern. The first part is a number divisible by 2. Then there are i-1 extra parts for odd numbers with 2 in the first position, second and so on. The hard part is to calculate the factors (2, 18, 162, ...).
Here is a function that returns a new factor for any i:
f(i) = 2 * 10^(i-2) - sum(10^(ix-1)*f(x), x from 2 to i-1) = 2 * 9^(i-2) [thx @m69] f(2) = 2 f(3) = 2*10 - (1*2) = 18 f(4) = 2*100 - (10*2 + 1*18) = 162 f(5) = 2*1000 - (100*2 + 10*18 + 1*162) = 1458
Thus, using this information, we can find the following algorithm:
Find the maximum number 10^i*2 that does not exceed the position. (If n is in the range [positionOf(10^i*2), positionOf(10^i*2) + (10^i)] , then we already know the solution: 10^i*2 + (n - positionOf(10^i*2)) . For example, if we find that I = 2, we know that the following 100 values ββare in the sequence: [201, 300], therefore, if 110 <= n <= 210, then the solution is 200 + (n-110) = n + 90.)
int nn = positionOf(10^i * 2); int s = 10^i * 2; for (int ii = i; ii >= 0; ii--) { for (int j = 1; j < 10; j++) { if (j == 1 || j == 6) { if (n <= nn + 10^ii) return s + nn - n; nn += 10^ii; s += 10^ii; int tmp = positionOf(10^ii); if (nn + tmp > n) break; nn += tmp; s += 10^ii; } else { int tmp = positionOf(10^ii * 2); if (nn + tmp > n) break; nn += tmp; s += 10^ii * 2; } } } return s;
This is only an unverified pseudocode (I know that you cannot use ^ in Java), ii = 1 or 0 should be considered as a special case, it is absent and how to find i isn is either shown or the answer will be too long.