compute method

List<Fraction> compute()

Returns a series of Fractions representing the egyptian fraction of the current fraction object.

Throws a FractionException if fraction is negative.

Implementation

List<Fraction> compute() {
  if (fraction.isNegative) {
    throw const FractionException('The fraction must be positive!');
  }

  // If the result is in the cache, then return it immediately.
  if (_cache.containsKey(fraction)) {
    return _cache[fraction]!;
  }

  // Computing the fraction
  final results = <Fraction>[];

  var numerator = fraction.numerator;
  var denominator = fraction.denominator;

  while (numerator > 0) {
    final egyptianDen = (denominator + numerator - 1) ~/ numerator;
    results.add(Fraction(1, egyptianDen));

    numerator = _modulo(-denominator, numerator);
    denominator *= egyptianDen;
  }

  // The value isn't in the cache at this point to we must add it
  _cache[fraction] = List<Fraction>.from(results);

  return results;
}