How to compute the total number of Powerball lottery combinations (5 out of 99 and 1 out of 26) in Rust

1 Answer

0 votes
/*
    This program computes the total number of Powerball lottery combinations:
        - Choose 5 distinct numbers out of 69
        - Choose 1 Powerball number out of 26

    Total combinations = C(69, 5) * 26

    It uses:
        - u128 for safe integer arithmetic
        - an efficient binomial coefficient function
        - a helper to format numbers with commas
*/

/// Computes C(n, k) using the multiplicative formula:
///
///     C(n, k) = Π (n - i + 1) / i   for i = 1..k
///
/// This avoids factorial overflow and floating‑point inaccuracies.
fn binomial(n: u128, k: u128) -> u128 {
    if k > n {
        return 0;
    }

    // Use symmetry: C(n, k) = C(n, n-k)
    let k = if k > n - k { n - k } else { k };

    let mut result: u128 = 1;

    for i in 1..=k {
        result = result * (n - i + 1) / i;
    }

    result
}

/// Formats a u128 with commas.
/// Example: 11238513 -> "11,238,513"
fn format_with_commas(value: u128) -> String {
    let s = value.to_string();
    let mut out = String::new();

    let mut count = 0;
    for ch in s.chars().rev() {
        if count == 3 {
            out.push(',');
            count = 0;
        }
        out.push(ch);
        count += 1;
    }

    out.chars().rev().collect()
}

fn main() {
    const MAIN_COUNT: u128 = 5;
    const MAIN_MAX: u128   = 69;
    const POWER_MAX: u128  = 26;

    // Compute C(69, 5)
    let main_combinations: u128 = binomial(MAIN_MAX, MAIN_COUNT);

    // Multiply by 26 Powerball choices
    let total_combinations: u128 = main_combinations * POWER_MAX;

    println!("Powerball combinations (5 out of 69 and 1 out of 26):");
    println!("C(69, 5) = {}", format_with_commas(main_combinations));
    println!("Total combinations = {}", format_with_commas(total_combinations));
}


/*
run:

Powerball combinations (5 out of 69 and 1 out of 26):
C(69, 5) = 11,238,513
Total combinations = 292,201,338

*/

 



answered Jul 29 by avibootz

Related questions

...