I have an array like this
[2, 3, 4, 5]
I want to find two numbers whose multiplication result is 6
I have an array like this
[2, 3, 4, 5]
I want to find two numbers whose multiplication result is 6
This prints all pairs of numbers in the list whose product equals 6.
const list = [2, 3, 4, 5];
for (var i = 0; i < list.length; i++) {
for (var j = i+1; j < list.length; j++) {
if (list[i] * list[j] == 6) {
console.log(list[i] + ' * ' + list[j] + ' = 6');
}
}
}
As pointed in a comment, there are more efficient solutions. Here is one of them, with the drawback that it is a little more complicated:
const list = [2, 3, 4, 5]
const res = 6;
const elems = new Set()
list.forEach(num => {
if (num == 0 && res == 0) {
console.log('0 times anything is 0');
} else if (res%num == 0 && elems.has(res/num)) {
console.log(num + ' * ' + res/num + ' = ' + res);
} else {
elems.add(num);
}
});
You can increase performance significantly, using the given solution. First, eliminate unused data then perform find algorithm.
const data = [2, 3, 4, 5];
const find = (data, result) => {
for (let k = 1; k < data.length; k = k + 1) {
for (let i = 0, j = data.length - 1; i < j; i++, j--) {
if (data[i] * data[j] === result) {
return [data[i], data[j]];
}
}
let temp = data[data.length - 1];
data[data.length - 1] = data[k];
data[k] = temp;
}
};
const findClean = (data, result) => {
return find(
data.filter((num) => result % num === 0),
result
);
};
console.log("find:" + find(data, 6));
console.log("find:" + find(data, 8));
console.log("find:" + find(data, 10));
console.log("find:" + find(data, 15));
console.log("findClean:" + findClean(data, 6));
console.log("findClean:" + findClean(data, 8));
console.log("findClean:" + findClean(data, 10));
console.log("findClean:" + findClean(data, 15));