while
?function solution(n) {
while (!n.every(x => x == n[0])) {
n.sort((a, b) => b - a).forEach((v, i) => n[i - 1] > m ? n[i - 1] % m != 0 ? n[i - 1] = n[i - 1] % m :
n[i - 1] = m : v, m = Math.min(...n))
}
return n[0] * n.length
}
reduce()
или добавлением условия в forEach()
? (() => {
const solution = (arr, iteration = 1) => {
if(arr.every(num => num === arr[0])) {
return arr[0] * arr.length;
}
const minNum = Math.min(...arr)
arr.forEach((num, i) => {
if(num > minNum) {
arr[i] = num % minNum || minNum;
}
});
console.log(`Iteration ${iteration}`, arr);
return solution(arr, iteration + 1);
}
console.log(solution([6,9,21]));
console.log(solution([56, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 142]));
})()
(() => {
const solution = (arr, iteration = 1) => {
const minNum = Math.min(...arr);
let hasDif = false;
arr.forEach((num, i) => {
if(num > minNum) {
hasDif = true;
arr[i] = num % minNum || minNum;
}
});
if(hasDif) {
console.log(`Iteration ${iteration}`, arr);
return solution(arr, iteration + 1);
}
return arr[0] * arr.length;
}
console.log(solution([6,9,21]));
console.log(solution([56, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 142]));
})()
(() => {
const solution = (arr) => {
let iteration = 1;
const baseSet = new Set(arr);
if(baseSet.size < 2) {
return arr[0] * arr.length;
}
const solve = (set) => {
const minNum = Math.min(...set);
const nextSet = new Set();
set.forEach((num, i) => {
if(num > minNum) {
nextSet.add(num % minNum || minNum);
}
});
if(nextSet.size < 2) {
return minNum * arr.length;
}
console.log(`Iteration ${iteration}`, arr);
return solve(nextSet);
}
return solve(baseSet);
}
console.log(solution([6,9,21]));
console.log(solution([56, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 142]));
})()