Skip to content

Instantly share code, notes, and snippets.

@raderj89
Last active March 15, 2016 06:28
Show Gist options
  • Save raderj89/ae524a1c502083c8f554 to your computer and use it in GitHub Desktop.
Save raderj89/ae524a1c502083c8f554 to your computer and use it in GitHub Desktop.
Sums of consecutive integers
/**
* 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