Find two numbers which, when multiplied, are equal to the input – Javascript Coding Question

A good way to test your mastery of the Javascript programming language is to indulge in some coding problems. Doing so improves your reflexes, makes you think out of the box, and can even help you land your dream job!

 

A question to get started:

 

“Build a function that takes in two parameters, the first one: an Array of integers; and the second: an Integer (we’ll call it “target”).

This function must find in its first parameter (the Array) two numbers that, when multiplied, are equal to the second parameter (the “target”). The function must then return the two numbers.”

 

Solution:

 

A way of solving this problem consists in:

 

  1. Looping through the integer Array.
    array.some(integer => {

    We use the “some” interator since other Javascript loops such as mapand forEach do not have a “stop loop” functionality. The “some” loop will stop as soon as the testing function returns true.

  2. Dividing each integer by the second parameter.
    let secondNumber = target / integer;
  3. The result of this division will be the second number, that must be also found in the integer Array.
    if(array.includes(secondNumber))
  4. If the second number is found, then both numbers will be returned by the function.
    resultingIntegers.push(integer, secondNumber);
  5. Since we need two numbers only, we’ll break out of the “some” loop by checking the length of the resultingIntegers array. Remember that the “some” iterator breaks when the testing function return equals true.
    return resultingIntegers.length === 2;

Full working code:

 

let integers = [2, 4, 1, 6, 5, 40, -1];

let findIntegersThatMultiplyTo = (array, target) => {
  let resultingIntegers = [];

  array.some(integer => {
    let secondNumber = target / integer;

    if (array.includes(secondNumber))
      resultingIntegers.push(integer, secondNumber);

    return resultingIntegers.length === 2;
  });

  return resultingIntegers;
};

document.write(findIntegersThatMultiplyTo(integers, 20));

Share your thoughts