farey static method

Iterable<Fraction> farey(
  1. int n, {
  2. bool ascending = true,
})

Iterable over the Farey sequence of order n.

Returns an ordered sequence of the reduced fractions between 0 and 1 with denominators less than or equal to order.

For details, see https://en.wikipedia.org/wiki/Farey_sequence.

Implementation

static Iterable<Fraction> farey(int n, {bool ascending = true}) sync* {
  if (n < 1) {
    throw ArgumentError.value(n, 'order', 'Expected positive');
  }
  var (a, b, c, d) = (ascending ? 0 : 1, 1, ascending ? 1 : n - 1, n);
  yield Fraction._(a, b);
  while (c <= n && ascending || a > 0 && !ascending) {
    final k = (n + b) ~/ d;
    (a, b, c, d) = (c, d, k * c - a, k * d - b);
    yield Fraction._(a, b);
  }
}