To produce all pairs (the catesian product) fom two enumerations, we need a version of Cantor's enumeration that includes zeros, and doesn't exclude pairs whose gcd is not one. 0,0 1,0 2,0 3,0 4,0 0,1 1,1 2,1 3,1 0,2 1,2 2,2 3,2 0,3 1,3 2,3 3,3 0,4 in Cantor's ordering we get n r c - - - 0 0,0 1 1,0 2 0,1 This gives us a formula: 3 2,0 4 1,1 n = (r+c+1)*(r+c)/2 + c 5 0,2 6 3,0 With some work, this can be reversed to give 7 2,1 a formula for r, c as a function of n 8 1,2 9 0,3 cantor(r, c) = (r+c+1)*(r+c)/2 + c 10 4,0 11 3,1 anticantor(n) = the corresponding (r,c) pair 12 2,2 13 1,3 14 0,4 etc The anti-Cantor calculation, n -> (r, c): diag = (int)floor(-0.5 + sqrt(1 + 8 * n) / 2); n0 = (diag + 1) * diag / 2.0; c = n - n0; r = diag - c;