Performing power operations on an array of numbers in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array of integers, arr, of even length.

Suppose a number num where −

num = (arr[0] * arr[0] + arr[1] * arr[1]) * (arr[2] * arr[2] + arr[3] * arr[3]) * … * (arr[n-2] * arr[n-2] + arr[n-1] * arr[n-1])

Where n is the length of the array.

Our function should find and return an array of two numbers [A, B] such that −

A2 + B2 = num

For instance, if the array is −

[1, 2, 3, 4]

Then num = ( 1 + 4 ) * (9 + 16) = 125

Then output should be −

[2, 11]

Because 22 + 112 = 125

Example

Following is the code −

 Live Demo

const arr = [1, 2, 3, 4];
const findMatchingSumArray = (arr = []) => {
   let squaredSum = 1;
   for(let i = 0; i < arr.length - 1; i += 2){
      const curr = arr[i];
      const next = arr[i + 1];
      squaredSum *= (Math.pow(curr, 2) + Math.pow(next, 2));
   };
   for(let k = 0; k * k < squaredSum; k++){
      for(let j = 0; (k * k) + (j * j) <= squaredSum; j++){
         if((k * k) + (j * j) === squaredSum){
            return [k, j];
         };
      };
   };
   return [];
};
console.log(findMatchingSumArray(arr));

Output

Following is the console output −

[2, 11]
raja
Published on 19-Apr-2021 07:37:58
Advertisements