如何在 JavaScript 中找到具有相同乘积的所有 2 对整数?

5 html javascript arrays popup syntax-error

我需要编写一个程序,当给定一个整数列表时,它会找到具有相同乘积的所有 2 对整数。即 2-pair 是 2 个不同的整数对,可以说 [(a,b),(c,d)],其中 a*b = c*d 但 a \xe2\x89\xa0 b \xe2\x89\xa0 c \xe2\x89\xa0 d.

\n\n

整数的范围应该是从 1 到 1024。我想要实现的是,当打开网页时,用户会收到一个弹出窗口提示,他将在其中输入整数数组,例如[1,2,3,7,8,9,6]从输入中输入[1,2,3,7,8,9,6]输出应该是,[(9,2),(3,6)]因为两者的计算结果都是18。

\n\n

到目前为止我所做的编码是非常基本的,可以在下面看到。到目前为止我所做的是弹出框警告输入等,但似乎无法理解如何让程序检查配对并给出总和。预先感谢这个社区帮助我更好地理解和学习 javascript!

\n\n

我在下面做了相当多的研究,绝对与我的问题不同,但已经完成了它们。

\n\n\n\n

代码:

\n\n

\r\n
\r\n
function evaluate() {\r\n  const input = prompt("Please enter the array of integers in the form: 1,2,3,1")\r\n    .split(\',\')\r\n    .map(item => item.trim());\r\n\r\n  function pairs(items) {\r\n  }\r\n\r\n  if (input == "" || input == null) {\r\n    document.writeln("Sorry, there is nothing that can be calculated.");\r\n  } else {\r\n\r\n    document.writeln("Your calculation is: ");\r\n    document.writeln(pairs(input) + " with a starting input string of: " + input);\r\n  }\r\n}\r\nevaluate()
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

Jon*_*lms 0

我们可以改变方程:

a * b = c * d | : b
a = c * d : b
Run Code Online (Sandbox Code Playgroud)

所以实际上我们只需要获取三个数字(b,c,d)的所有不同组合并检查结果(a)是否也在给定范围内:

while(true){
  // shuffle
  const [b, c, d] = items;
  const a = c * d / b;
  if(items.includes(a + ""))
     return true;
}
return false;
Run Code Online (Sandbox Code Playgroud)

现在你只需要打乱数组即可经历所有不同的组合。你可以在这里找到一个算法