You've hit the exact problem: "cannot mix bigint and other types".
Your factorial function f correctly returns BigInt values (indicated by 1n and the multiplication involving BigInt(n)). However, in your choose function:
let choose = (a,b) => f(a)/(f(b)*(a-b))
f(a) and f(b) return BigInt.
a and b are standard JavaScript numbers (like 49 and i).
(a-b) results in a standard JavaScript number.
f(b) * (a-b) tries to multiply a BigInt (f(b)) by a standard number (a-b), which causes the TypeError.
Also, your result variable is initialized as a standard number (0), but you're trying to add BigInt values to it, which will also cause a type error eventually.
Here's the corrected version using BigInt consistently and a more efficient way to calculate combinations:
// More efficient factorial function that works directly with BigInt
// (Your original factorial function also works if inputs are consistently BigInt)
const factorial = n => {
// Ensure n is BigInt for calculations
const numN = typeof n === 'bigint' ? n : BigInt(n);
if (numN < 0n) return NaN; // Use BigInt literal for comparison
if (numN === 0n) return 1n; // Base case: 0! is 1 (as BigInt)
let result = 1n;
for (let i = 2n; i <= numN; i++) { // Loop with BigInt
result *= i;
}
return result;
};
// Efficient function to calculate "n choose k" (Binomial Coefficient) using BigInt
// C(n, k) = n! / (k! * (n-k)!)
// Optimized calculation: C(n, k) = (n * (n-1) * ... * (n-k+1)) / (k * (k-1) * ... * 1)
const choose = (n, k) => {
// Ensure inputs are BigInt
const numN = BigInt(n);
const numK = BigInt(k);
// Handle invalid inputs for combinations
if (numK < 0n || numK > numN) {
return 0n; // n choose k is 0 if k is out of range
}
// Base cases: n choose 0 is 1, n choose n is 1
if (numK === 0n || numK === numN) {
return 1n;
}
// Optimization: C(n, k) == C(n, n-k)
// Calculate with the smaller k value to reduce operations
if (numK > numN / 2n) {
k = numN - numK;
}
let result = 1n;
// Calculate using the optimized formula
// We multiply and divide in each step to keep numbers smaller
for (let i = 1n; i <= numK; i++) {
result = result * (numN - i + 1n) / i;
}
return result;
};
// Initialize result as a BigInt
let result = 0n;
// Loop and sum the combinations
// We are calculating Sum_{i=1}^{49} C(49, i)
for (let i = 1; i <= 49; i++) {
result += choose(49, i);
}
console.log(`The sum is: ${result}`);
// --- Verification ---
// Mathematical property: Sum_{i=0}^{n} C(n, i) = 2^n
// So, Sum_{i=1}^{49} C(49, i) = (Sum_{i=0}^{49} C(49, i)) - C(49, 0)
// = 2^49 - 1
const expectedSum = 2n ** 49n - 1n;
console.log(`Expected sum (2^49 - 1): ${expectedSum}`);
console.log(`Results match: ${result === expectedSum}`);