Skip to content

Instantly share code, notes, and snippets.

@RandyMcMillan
Last active January 10, 2025 16:28
Show Gist options
  • Save RandyMcMillan/a405a295c335b9671fe8447a5e3e26fa to your computer and use it in GitHub Desktop.
Save RandyMcMillan/a405a295c335b9671fe8447a5e3e26fa to your computer and use it in GitHub Desktop.
binomial.rs
//use std::cmp::min;
/// Calculates the binomial coefficient (n choose k).
///
/// # Arguments
///
/// * `n`: The total number of items.
/// * `k`: The number of items to choose.
///
/// # Returns
///
/// The binomial coefficient as a usize.
fn binomial_coefficient(n: usize, k: usize) -> usize {
if k > n {
return 0;
}
let mut result = 1;
for i in 0..k {
result = result * (n - i) / (i + 1);
}
result
}
/// Calculates the binomial expansion of (x + y)^n.
///
/// # Arguments
///
/// * `n`: The exponent.
/// * `x`: The first term.
/// * `y`: The second term.
///
/// # Returns
///
/// A vector containing the coefficients of the expansion.
fn binomial_expansion(n: usize, x: i32, y: i32) -> Vec<i32> {
let mut coefficients = Vec::with_capacity(n + 1);
for k in 0..=n {
let coefficient = binomial_coefficient(n, k) as i32 * x.pow((n - k).try_into().unwrap()) * y.pow(k.try_into().unwrap());
coefficients.push(coefficient);
}
coefficients
}
fn main() {
let n = 5;
let x = 2;
let y = 3;
let coefficients = binomial_expansion(n, x, y);
println!("Binomial expansion of ({x} + {y})^n:");
for (i, coefficient) in coefficients.iter().enumerate() {
if *coefficient != 0 {
print!("{coefficient}");
if i < n {
print!("*x^{{{}}}{} ", n - i, if i > 0 { " + " } else { "" });
}
}
}
println!();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment