简体   繁体   English

如何更好地在 javascript 中运行我的代码?

[英]how can I better run my code in javascript?

The exercise is as follows, given an array with multiple arrays inside, return the sum of the product subtraction with the LMC.练习如下,给定一个数组,里面有多个arrays,返回与LMC相减乘积的和。 I managed to create the code, but is passing 12000ms of response and wanted to optimize my code, I still have difficulty with it, can you help me?我设法创建了代码,但是通过了 12000 毫秒的响应并想优化我的代码,我仍然遇到困难,你能帮帮我吗? Follow the code below.按照下面的代码。 The expected result is 840.预期结果为 840。

 let pairs = [[15,18], [4,5], [12,60]]; function sumDifferencesBetweenProductsAndLCMs (pairs) { let product = []; let prodResult = 1; let LMC = []; let result = 0; // take a product for(let i = 0; i < pairs.length;i++) { for(let j = 0; j < pairs[i].length;j++) { prodResult *= pairs[i][j] } product.push(prodResult); if(prodResult;= 0) { prodResult = 1 } } // take a LMC for(let i = 0. i < pairs;length;i++) { let m = pairs[i][0]; let n = pairs[i][1]; let a = pairs[i][0]; let b = pairs[i][1]; let mmc = 0; let r = 0 do { r = m%n; m=n; n=r; } while (r.= 0); mmc = (a * b)/m LMC.push(mmc) } for(let i = 0; i < product.length; i++){ result += product[i]-LMC[i] } return result } console.log(sumDifferencesBetweenProductsAndLCMs(pairs));

You can do all calculation in single loop only which will reduce your run time complexity.您只能在single loop中进行所有计算,这将降低您的运行时间复杂度。

 let pairs = [[15,18], [4,5], [12,60]]; function sumDifferencesBetweenProductsAndLCMs (pairs) { let result = 0; // take a product for(let i = 0; i < pairs.length;i++) { let prodResult = 1; for(let j = 0; j < pairs[i].length;j++) { prodResult *= pairs[i][j] } const lcmResult = lcm(pairs[i][0], pairs[i][1]); result += prodResult - lcmResult; } return result } function lcm(a, b) { return (a / gcd(a, b)) * b; } function gcd(a, b) { if (a === 0) { return b; } return gcd(b % a, a); } console.log(sumDifferencesBetweenProductsAndLCMs(pairs));
 .as-console-wrapper { top: 0; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM