Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Performing power operations on an array of numbers in JavaScript
We need to write a JavaScript function that takes an array of integers with even length and performs a specific power operation to find two numbers whose squares sum to a calculated value.
Problem Statement
Given an array of integers with even length, we calculate:
num = (arr[0]² + arr[1]²) × (arr[2]² + arr[3]²) × ... × (arr[n-2]² + arr[n-1]²)
Our function should return an array [A, B] such that A² + B² = num.
Example Walkthrough
For array [1, 2, 3, 4]:
- First pair: 1² + 2² = 1 + 4 = 5
- Second pair: 3² + 4² = 9 + 16 = 25
- num = 5 × 25 = 125
- Find A, B where A² + B² = 125
- Result: [2, 11] because 2² + 11² = 4 + 121 = 125
Solution
const arr = [1, 2, 3, 4];
const findMatchingSumArray = (arr = []) => {
let squaredSum = 1;
// Calculate the product of sum of squares for each pair
for(let i = 0; i
[2, 11]
Verification: 125
How It Works
The algorithm works in two phases:
-
Calculate the target sum: Iterate through pairs of array elements, square each element, sum the squares in each pair, then multiply all pair sums together.
-
Find the solution: Use nested loops to test all combinations of integers k and j until we find k² + j² equals our target sum.
Testing with Different Arrays
// Test with different arrays
const testCases = [
[1, 2, 3, 4],
[1, 1, 1, 1],
[2, 3, 4, 5]
];
testCases.forEach(testArr => {
const result = findMatchingSumArray(testArr);
console.log(`Array: [${testArr.join(', ')}] => Result: [${result.join(', ')}]`);
});
Array: [1, 2, 3, 4] => Result: [2, 11]
Array: [1, 1, 1, 1] => Result: [0, 2]
Array: [2, 3, 4, 5] => Result: [1, 18]
Conclusion
This algorithm efficiently solves the power operation problem by first calculating the target sum from paired squares, then using a brute-force search to find two integers whose squares sum to that target. The nested loop approach ensures we find the solution systematically.
Advertisements
