I want to solve for n
in the expression (binomial coefficient):
\$y=\frac{n^2+n}2\$
let y = (Math.pow(n, 2) + n) / 2;
I know the \$y\$ value, but I want to compute \$n\$.
Here is what I have so far, but I would want to know if there was a way to compute the value rather than look it up. In this example, I have to lookup the max value in a reversed array that is constrained by a length of 10.
Edit: Here is another avenue I took (still not an expression):
// Iterative
const toBase = n => {
if (n < 1) return 0;
let value = n, delta = 0;
while (value > 0) value -= delta++;
return delta - 1;
};
// Recursive
const toBase = (n, delta = 0) =>
n === 0 && delta === 0
? 0
: n < 1
? delta - 1
: toBase(n - delta, delta + 1);
const MAX_BASES = 10;
const range = n => new Array(MAX_BASES).fill(0);
const binomialCoefficient = n => (Math.pow(n, 2) + n) / 2;
const baseMax = range(MAX_BASES).map((v, i) => binomialCoefficient(i));
const toBase = n => baseMax.indexOf([...baseMax].reverse().find(max => n > max)) + 1;
const main = () => {
const inputs = getInputs().trim().split(/\n/)
.map(l => l.trim().split(/\s+/g).map(v => parseInt(v.trim(), 10)))
.filter(([v]) => !isNaN(v));
inputs.forEach(input => validate(...input));
};
const validate = (n, expected) => {
const actual = toBase(n);
if (actual !== expected) {
throw new Error(`${actual} !== ${expected} for n=${n}`);
}
console.log(`${n}: ${expected} === ${actual} | valid!`);
};
const getInputs = () => `
0 0
1 1
2 2
3 2
4 3
5 3
6 3
7 4
8 4
9 4
10 4
11 5
12 5
13 5
14 5
15 5
16 6
17 6
18 6
19 6
20 6
21 6
22 7
23 7
24 7
25 7
26 7
27 7
28 7
29 8
30 8
31 8
32 8
33 8
34 8
35 8
36 8
`;
main();
.as-console-wrapper { top: 0; max-height: 100% !important; }
14
14 - 1 = 13
13 - 2 = 11
11 - 3 = 8
8 - 4 = 4
4 - 5 = -1
Background: I noticed a pattern which looked very similar to a factorial expression, but with addition rather than multiplication. After some research, I stumbled upon the following question which lead me in the right direction: