Editorial
Suppose . If , the last binary bit of is and the previous pair is . If , the last bit is and the previous pair is .
Repeated subtraction can be too slow. When , let and subtract at once; this removes trailing zero bits. The case is symmetric. Since and are coprime, the process ends at .
Reattach the removed bit runs in reverse order. Appending zeros changes to , while appending ones changes it to . Work modulo . The number of quotient steps is logarithmic, so the time complexity is . Solution written by GPT5.6