Partitions, Coins, and Others

Coins

The number of ways to obtain a given sum using a given set of coins.

Problem 31 from Project Euler

Algorithm:

Example:

Consider the example of computing the number of ways to obtain the sum 4, using coins (1, 2, 3):

Estimation:

Code:

def countWays(coins: Array[Int], sum: Int): Long =
  val ways = Array.fill(sum + 1)(0L)
  ways(0) = 1
  for
    coin <- coins
    i    <- coin to sum
  do ways(i) += ways(i - coin)
  ways(sum)

countWays(Array(1, 2, 5, 10, 20, 50, 100, 200), 200)
// 73682

Partitions

Number of ways to write n as a sum of positive integers.

Code:

def partition(number: Int): BigInt =
  val array = new Array[BigInt](number + 1)
  array(0) = BigInt(1)
  if number >= 1 then array(1) = BigInt(1)
  if number >= 2 then array(2) = BigInt(2)

  def partitionPart(s: Int, n: Int, pS: BigInt): BigInt =
    @tailrec
    def loop(k: Int, p: BigInt): BigInt =
      val op = k * (3 * k - 1) / 2
      if op > n then p
      else
        val newP =
          if (k + 1) % 2 == 0 then p + array(n - op)
          else p - array(n - op)
        loop(k + s, newP)

    loop(s, pS)

  (3 to number).foreach: n =>
    val p = partitionPart(1, n, BigInt(0))
    array(n) = partitionPart(-1, n, p)
  array(number)
end partition

partition(1000)
// BigInt("24061467864032622473692149727991")

Links: