Last active
March 15, 2016 06:28
-
-
Save raderj89/ae524a1c502083c8f554 to your computer and use it in GitHub Desktop.
Sums of consecutive integers
This file contains hidden or 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
/** | |
* Given the number of consecutive integers and the total of the integers, | |
* return the consecutive integer at the requested position. | |
* | |
* @param {int} x number of consecutive integers | |
* @param {int} y sum of consecutive integers | |
* @param {int} n position of requested integer | |
* @return {int} consecutive integer at requested position | |
*/ | |
function position(x, y, n) { | |
let numList = []; | |
for(let a = 0; a < x; a++) numList.push(a); | |
let currentSum = getSum(numList); | |
if (currentSum === y) return numList[n]; | |
let remainder = Math.floor((y - currentSum) / x); | |
return numList.map((el) => el + remainder))[n]; | |
} | |
function getSum(array) { | |
return array.reduce((prev, current) => prev + current); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment