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

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:
        - BigInt for safe integer arithmetic
        - an efficient binomial coefficient function
        - a helper to format numbers with commas
*/

object PowerballCombinations {

  /*
      binomial(n, k):
      Computes C(n, k) using the multiplicative formula:

          C(n, k) = Π (n - i + 1) / i   for i = 1..k

      Implemented using BigInt to avoid overflow.
  */
  def binomial(n: Int, k: Int): BigInt = {
    if (k > n) return BigInt(0)

    val kk = math.min(k, n - k) // symmetry: C(n, k) = C(n, n-k)
    var result = BigInt(1)

    for (i <- 1 to kk) {
      result = result * BigInt(n - i + 1) / BigInt(i)
    }

    result
  }

  /*
      formatWithCommas(value):
      Formats a BigInt with commas.
  */
  def formatWithCommas(value: BigInt): String = {
    val s = value.toString
    s.reverse.grouped(3).mkString(",").reverse
  }

  def main(args: Array[String]): Unit = {
    val MAIN_COUNT = 5
    val MAIN_MAX   = 69
    val POWER_MAX  = 26

    // Compute C(69, 5)
    val mainCombinations: BigInt = binomial(MAIN_MAX, MAIN_COUNT)

    // Multiply by 26 Powerball choices
    val totalCombinations: BigInt = mainCombinations * POWER_MAX

    println("Powerball combinations (5 out of 69 and 1 out of 26):")
    println(s"C(69, 5) = ${formatWithCommas(mainCombinations)}")
    println(s"Total combinations = ${formatWithCommas(totalCombinations)}")
  }
}



/*
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

...