Rounding rounding at (0, 1) to the nearest unit fraction

What is a good algorithm for the next problem?

Given a rational a / b strictly between 0 and 1, we find a natural n that minimizes | a / b - 1 / n |.

The simplest algorithm I can imagine is to compare a / b and 1 / m for m = b, b - 1, ..., stopping when a / b ≤ 1 / m, and then compare | a / b - 1 / m | and | a / b - 1 / (m + 1) |. This is O (b). Can you do better?

+5
source share
3 answers

Let k = gender (b / a), and then n is either k or k + 1. Try 2 candidates and see who wins. This is O (1).

, 1/(k + 1) <= a/b <= 1/k, , , k <= b/a <= k + 1.

+7

, O (1), . (0, 1]

1 / (a0 + 1 / (a1 + 1 / (a2 + 1 / (... an))))

, . -, , . ,

1 / a0

a/b 1/a0 1/(a0 + 1). , a0, , , .

, a0: b/a. , :

  • x = b/a, .
  • , 1/x 1/(x + 1) a/b .

a b , O (1) .

+1

, .

a / b 0 <= x <= 1, :

int Rationalize(double x)
{
    int n1 = floor(1 / x);
    int n2 = ceiling(1 / x);

    double e1 = abs(x - 1.0 / n1);
    double e2 = abs(x - 1.0 / n2);

    if (e1 < e2) return n1;
    else return n2;
}

( , )

0

All Articles