You are given an integer n and a rational p/q (p and q are integers).
How do you compare sqrt(n) and p/q?
Solution 1: sqrt(n) <= (double) p / q
Should work, but calls sqrt
which is slower than just using multiplication/division.
Solution 2: (double) n * q * q <= p * p
Better, but I can't help thinking that because we are using floats, we might get an incorrect answer if p/q is very close to sqrt(n). Moreover, it requires converting integers to floats, which is (marginally) slower than just working with integers.
Solution 3: n*q*q <= p*p
Even better, but one runs into trouble if p and q get big because of overflow (typically, if p or q >= 2^32 when working with 64 bits integers).
Solution 4: Use solution 3 with a bignum library / in a programming language that has unbound integers.
Solution 5: (q / p) * n <= p / q
Successfully avoids any overflow problems, but I am not sure that this is correct in all cases, because of integer division...
So... I would happily go with solution 2 or 4, but I was wondering if anyone has clever tricks to solve this problem or maybe a proof (or counter example) that solution 5 works (or not).