← RoseCode

ROSECODE 335

Diagonal Enumeration

Philippe_57721 · Programming ·

You certainly know of this nice proof of the equipotence between the set of integers and the set of rational numbers.

We consider an infinite grid numbered horizontally and vertically with integers:

We run through this grid according the above pattern and count each pair (i,j) where i and j are coprime.

We obtain the following bijection:
    1 - 11=1

    2 - 12
    3 - 21=2

    4 - 31=3
    5 - 13

    6 - 14
    7 - 23
    8 - 32
    9 - 43

    10 - 51=5
    11 - 15

    12 - 16
    13 - 25
    14 - 34
    15 - 41=4
    16 - 52
    17 - 61=6

    If we run through the upper diagonal matrix of a 6×6 grid, we get 17 rationals.

    How many rationals can we count in the upper diagonal matrix of a 109×109 grid?

    You are given: 303964542391 for a 106×106 grid
    [My timing: < 90 sec]