Since it is trivial to reduce to co-prime pairs, let's assume are co-prime. Also by definition of rational numbers we can say that "infinite -1" is not a valid output. If prime factors of are also prime factors for then the representation of is finite. Otherwise, there exists some prime factors of that doesn't divide . It can be easily shown that has similar period length as , so we mainly focus on in base for now. Let's further divide the problem in 2 cases as following:
: where . Then . Thus the length of the repetition is , this is also called the order of modulo . And the output will be "infinite 0 r".
: Let where . Now where has finite representation in base and is solved in previous case. One can verify that the repetition of gets shifted by the length of the representation of . Hence output is "infinite l r" where is the length of .
At this point there should be some algorithmic task to find as defined above, which can be found by either prime factorizing or repeatedly using gcd to seperate all common prime factors. And to find order one can utilze euler totient theorem and the fact if then , so take the divisors of and check if .