Good Bitstrings
Time limit2sMemory limit1024 MB
Given A and B, count the prefixes of gen_string(A, B) that also equal gen_string(x, y) for some positive integers x and y.
- Level
Hard8 of 10
- Topics
- Number theory, Math, Divide and conquer
- Solved
- No attempts yet
Statement
For positive integers and , the function gen_string(a,b) is defined by the following Python code.
def gen_string(a: int, b: int):
res = ""
ia, ib = 0, 0
while ia + ib < a + b:
if ia * b ≤ ib * a:
res += '0'
ia += 1
else:
res += '1'
ib += 1
return res
The equivalent C++ code is below.
string gen_string(int64_t a, int64_t b) {
string res;
int ia = 0, ib = 0;
while (ia + ib < a + b) {
if ((__int128)ia * b ≤ (__int128)ib * a) {
res += '0';
ia++;
} else {
res += '1';
ib++;
}
}
return res;
}
When the loop ends, equals and equals . So the function returns a bitstring of length with exactly zeroes and ones. For example, gen_string(4,10)=01110110111011.
Call a bitstring good if there exist positive integers and such that = gen_string(,). Given positive integers and (), count the good prefixes of gen_string(,).
For example, gen_string(4,10) has 6 good prefixes:
x = 1 | y = 1 | gen_string(x, y) = 01
x = 1 | y = 2 | gen_string(x, y) = 011
x = 1 | y = 3 | gen_string(x, y) = 0111
x = 2 | y = 5 | gen_string(x, y) = 0111011
x = 3 | y = 7 | gen_string(x, y) = 0111011011
x = 4 | y = 10 | gen_string(x, y) = 01110110111011
Input
The first line contains (), the number of test cases. Each of the next lines contains two integers and .
Output
For each test case, print the answer on a new line.