Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Expanding binomial expression using JavaScript
We need to write a JavaScript function that expands binomial expressions of the form (ax+b)^n, where a and b are integers, x is a variable, and n is a natural number. The function returns the expanded polynomial as a string.
Problem Statement
Given an expression like (8a+6)^4, we need to expand it using the binomial theorem. The result should be in the form ax^b+cx^d+ex^f... with coefficients and powers in decreasing order.
Understanding the Binomial Theorem
The binomial theorem states that (x+y)^n = ?(C(n,k) * x^(n-k) * y^k) where C(n,k) is the binomial coefficient.
Implementation
const str = '(8a+6)^4';
const trim = value => value === 1 ? '' : value === -1 ? '-' : value;
const factorial = (value, total = 1) =>
value <= 1 ? total : factorial(value - 1, total * value);
const find = (str = '') => {
let [op1, coefficient, variable, op2, constant, power] = str
.match(/(\W)(\d*)(\w)(\W)(\d+)..(\d+)/)
.slice(1);
power = +power;
if (!power) {
return '1';
}
if (power === 1) {
return str.match(/\((.*)\)/)[1];
}
coefficient = op1 === '-'
? coefficient
? -coefficient
: -1
: coefficient
? +coefficient
: 1;
constant = op2 === '-' ? -constant : +constant;
const factorials = Array.from({ length: power + 1 }, (_, i) => factorial(i));
let result = '';
for (let i = 0, p = power; i <= power; ++i, p = power - i) {
let judge = factorials[power] / (factorials[i] * factorials[p]) *
(coefficient ** p) * (constant ** i);
if (!judge) {
continue;
}
result += p
? trim(judge) + variable + (p === 1 ? '' : `^${p}`)
: judge;
result += '+';
}
return result.replace(/\+\-/g, '-').replace(/\+$/, '');
};
console.log(find(str));
4096a^4+6144a^3+3456a^2+864a+81
How It Works
The function uses regular expressions to parse the input expression, extracting the coefficient, variable, constant, and power. It then applies the binomial theorem using precomputed factorials for efficiency.
Key Components
| Function | Purpose |
|---|---|
trim() |
Formats coefficients (removes 1, shows - for -1) |
factorial() |
Calculates factorials recursively |
find() |
Main function that parses and expands the expression |
Example Breakdown
For (8a+6)^4:
- Coefficient a = 8, constant b = 6, power n = 4
- Each term follows: C(4,k) * (8a)^(4-k) * 6^k
- Results in 5 terms with decreasing powers of a
Conclusion
This implementation efficiently expands binomial expressions using the mathematical binomial theorem. The function handles coefficient formatting and produces clean polynomial output in standard mathematical notation.
