Unique integers that sum up to 0

Write a function that, given an integer N (1 ≤ N ≤ 100), returns an array containing N unique integers that sum up to 0. The function can return any such array.

For example, given N = 4, the function could return [1, 0, −3, 2] or [−2, 1, −4, 5]. The answer [1, −1, 1, 3] would be incorrect (because value 1 occurs twice). For N = 3 one of the possible answers is [−1, 0, 1] (but there are many more correct answers).

function uniqueIntegers(N) {
    result = [];
    var x = Math.floor(N / 2);
    var i = 0;
    if (N % 2 === 0) { // even
        i = 0;
    } else { // odd
        result[0] = 0;
        i = 1;
    }
    while (i < N) {
        result[i] = x;
        result[i + 1] = -1 * x;
        i += 2;
        x--;
    }
    return result;
}

Leave a Reply

Your email address will not be published. Required fields are marked *