Problem
We are required to write a JavaScript function that takes in an array of positive integers. We can transform its elements by running the following operation on them as many times as required −
if arr[i] > arr[j] then arr[i] = arr[i] - arr[j]
When no more transformations are possible, our function should return its sum.
Example
Following is the code −
const arr = [6, 9, 21]; const smallestSum = (arr = []) => { const equalNums = arr => arr.reduce((a, b) => { return (a === b) ? a : NaN; }); if(equalNums(arr)){ return arr.reduce((a, b) => { return a + b; }); }else{ const sorted = arr.sort((a, b) => { return a-b; }); const last = sorted[arr.length-1] - sorted[0] sorted.pop(); sorted.push(last); return smallestSum(sorted); }; }; console.log(smallestSum(arr));
Output
Following is the console output −
9