egyptian.js 585 B

123456789101112131415161718192021222324
  1. /*
  2. Fraction.js v5.0.0 10/1/2024
  3. https://raw.org/article/rational-numbers-in-javascript/
  4. Copyright (c) 2024, Robert Eisele (https://raw.org/)
  5. Licensed under the MIT license.
  6. */
  7. const Fraction = require('fraction.js');
  8. // Based on http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fractions/egyptian.html
  9. function egyptian(a, b) {
  10. var res = [];
  11. do {
  12. var t = Math.ceil(b / a);
  13. var x = new Fraction(a, b).sub(1, t);
  14. res.push(t);
  15. a = Number(x.n);
  16. b = Number(x.d);
  17. } while (a !== 0n);
  18. return res;
  19. }
  20. console.log("1 / " + egyptian(521, 1050).join(" + 1 / "));