Created
October 12, 2017 07:16
-
-
Save unilecs/23b947deb50ca0e996a2fb48ab916843 to your computer and use it in GitHub Desktop.
Get two removed elements in array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getRemovedElementInArray(arr, n) { | |
const totalSum = n*(n + 1) / 2; // формула арифмитческой прогрессии | |
let totalP = 1; | |
for(let i=1; i<=n; i++) { | |
totalP *= i; | |
} | |
// находим сумму и произведение элементов массива | |
let arrSum = 0, arrP = 1; | |
for(let i=0; i<arr.length; i++) { | |
arrSum += arr[i]; | |
arrP *= arr[i] !== 0 ? arr[i] : 1; | |
} | |
let sumTwoElements = totalSum - arrSum; | |
let pTwoElements = totalP / arrP; | |
// формула корня квадратного уравнения | |
let first = Math.round((sumTwoElements + Math.sqrt(sumTwoElements*sumTwoElements - 4*pTwoElements)) / 2); | |
let second = sumTwoElements - first; | |
return [first, second]; | |
} | |
const n = 10; | |
const arr = [1, 2, 3, 4, 5, 6, 7, 0, 0, 10]; | |
console.info(getRemovedElementInArray(arr, n)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment