Factorial

The n-factorial is a quantity expressed as: \(n! = 1 \cdot 2 \cdot ... \cdot n = \prod_{k=1}^{n}k \).

For example, 5-factorial equals 5! = 120.

Here \(0! = 1\) — given this convention, it is clear that the main identity \(n! = (n − 1)!n\) holds for all positive integers n.

Computing factorial

Given a number n. Compute n!.

Algorithm:

Example:

Example computation for n = 5:

Estimation:

Code:

def factorial(n: Int): Long =
  (2 to n).foldLeft(1L)(_ * _)

factorial(8)
// 40320

Approximate value using Stirling's formula

Algorithm:

Stirling's formula allows computing an approximate value of factorial: \(n!\approx \sqrt{2\pi n}\left ( \frac{n}{e} \right )^{n}\)

The relative error of calculations using this formula is approximately \(\frac{1}{12n}\).

Example:

Example of computing factorial using Stirling's formula for \(n = 10\):

Estimation:

Code:

def approximateFactorial(n: Int): BigInt =
  (BigDecimal(math.sqrt(2 * math.Pi * n)) *
    BigDecimal(n / math.E).pow(n)).toBigInt

approximateFactorial(8)
// BigInt(39902)

More precise approximation

Algorithm:

A more precise formula:

\(n! = \sqrt{2\pi n}\left ( \frac{n}{e} \right )^{n}(1 + \frac{1}{12n} + \frac{1}{288n^{2}} - \frac{139}{51840n^{3}} - \frac{571}{2488320n^{4}} + O(\frac{1}{n^{5}}))\)

Estimation:

Code:

def approximateFactorial2(n: Int): BigInt =
  (BigDecimal(math.sqrt(2 * math.Pi * n)) *
    BigDecimal(n / math.E).pow(n) *
    (1 + 1 / BigDecimal(12.0 * n) + 1 / BigDecimal(288.0 * n * n) -
      139 / BigDecimal(51840.0 * n * n * n) -
      571 / BigDecimal(2488320.0 * n * n * n * n))).toBigInt

approximateFactorial2(8)
// BigInt(40319)

Prime factorization of factorial

Algorithm:

A prime number \(p\) is a divisor of \(n!\) with multiplicity \(\mu = \left \lfloor \frac{n}{p} \right \rfloor + \left \lfloor \frac{n}{p^{2}} \right \rfloor + \left \lfloor \frac{n}{p^{3}} \right \rfloor + ... = \sum_{k > 0}^{}\left \lfloor \frac{n}{p^{k}} \right \rfloor\).

This formula allows decomposing factorial into prime factors.

Example:

Consider the example of computing the multiplicity of the prime number \(p = 3\) in factorial \(n = 10\).

Formula:

\(\mu = \left \lfloor \frac{n}{p} \right \rfloor + \left \lfloor \frac{n}{p^{2}} \right \rfloor + \left \lfloor \frac{n}{p^{3}} \right \rfloor + ... = \sum_{k > 0}^{}\left \lfloor \frac{n}{p^{k}} \right \rfloor \)

Estimation:

Code:

def primeFactor(n: Int, p: Int): Int =
  @tailrec
  def loop(pj: Int, acc: Int): Int =
    if pj == 0 then acc
    else
      val next = pj / p
      loop(next, acc + next)
  loop(n, 0)

primeFactor(1000, 3)
// 498

Links: