[My Computational Complexity Web Log] Counting the Rationals Quickly
In the November 1989 issue of American Mathematical Monthly Yoram Sagher presented a note "Counting the Rationals" giving a simple 1-1 mapping from the positive rationals onto the positive integers. Let m/n be a rational with gcd(m,n)=1. Let q1, ..., qk be the prime factors of n. Sagher defined his 1-1 mapping as f(m/n) = m2n2/ (q1q2··· qk)With this mapping, Sagher notes you can easily determine the 1015th positive rational as 10-8.
Unfortunately inverting Sagher's function appears to require factoring. Can one find a 1-1 mapping from the positive integers onto the positive rationals that is easy to compute in both directions? Think about it or keep reading for my solution.
Let p(i,j) = i + j(j-1)/2. The function p is an easily computable and invertible bijection from pairs (i,j) with 1≤i≤j to the positive integers. We define our 1-1 mapping from the positive integers to the positive rationals by the following algorithm.
- Input: n
- Find i and j such that n = p(i,j).
- Let g = gcd(i,j) (easily computable via Euclid's algorithm)
- Let u = i/g and v=j/g.
- Output: g-1+u/v
Posted by Lance Fortnow to My Computational Complexity Web Log at 3/1/2004 08:48:31 AM