- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding smallest sum after making transformations in JavaScript
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
Advertisements