题解 | #将真分数分解为埃及分数#
将真分数分解为埃及分数
https://www.nowcoder.com/practice/e0480b2c6aa24bfba0935ffcca3ccb7b
网友有奇招!!!
const rl = require("readline").createInterface({ input: process.stdin }); var iter = rl[Symbol.asyncIterator](); const readline = async () => (await iter.next()).value; void (async function () { // Write your code here while ((line = await readline())) { let [fenzi, fenmu] = line.split("/"); // 第一种偷懒的方法,不推荐:5/11 = 1/11+1/11+1/11+1/11+1/11 // let str = ''; // for(let i=0; i<fenzi; i++){ // str = str + '1/' + fenmu + '+'; // } // str = str.substring(0,str.length-1); // console.log(str); // 第二种,贪婪算法 let str = ""; if (fenmu % fenzi == 0) { let jianhua = fenmu / fenzi; str = "1/" + jianhua; } else { while (fenzi != 1) { // 先用网友妙法走一遍 3/110 分成 1/110 和 2/110, 其中2/110 = 1/55,直接就结束了! let jianyi = fenzi - 1; if (fenmu % jianyi == 0) { str = str + "1/" + (fenmu / jianyi) + "+" + "1/" + fenmu; fenzi = 1; } else { // 网友妙法走不通,就走下面的循环 let zheng_new_fm = Math.floor(fenmu / fenzi) + 1; // 2 let zxgbs = zuiXiaoGongBeiShu(fenmu, zheng_new_fm); // 22 let xucheng = zxgbs / fenmu; // 22/11 = 2 let fenzi_chenghou = fenzi * xucheng; // 8*2 = 16; let beijian = zxgbs / zheng_new_fm; // 22/2 = 11; let left = fenzi_chenghou - beijian; str = str + "1/" + zheng_new_fm + "+"; fenzi = left; fenmu = zxgbs; if (fenzi == 1) { str = str + "1/" + zxgbs; } } } } console.log(str); } })(); function zuiDaGongYueShu(n, m) { // 辗转相除法 求最大公约数 while (m !== 0) { let yushu = n % m; n = m; m = yushu; } return n; } function zuiXiaoGongBeiShu(n, m) { // 求最小公倍数 return (n * m) / zuiDaGongYueShu(n, m); }