How to resolve the algorithm Lah numbers step by step in the D programming language

Published on 12 May 2024 09:40 PM
#D

How to resolve the algorithm Lah numbers step by step in the D programming language

Table of Contents

Problem Statement

Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets. Lah numbers are closely related to Stirling numbers of the first & second kinds, and may be derived from them. Lah numbers obey the identities and relations:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Lah numbers step by step in the D programming language

Source code in the d programming language

import std.algorithm : map;
import std.bigint;
import std.range;
import std.stdio;

BigInt factorial(BigInt n) {
    if (n == 0) return BigInt(1);
    BigInt res = 1;
    while (n > 0) {
        res *= n--;
    }
    return res;
}

BigInt lah(BigInt n, BigInt k) {
    if (k == 1) return factorial(n);
    if (k == n) return BigInt(1);
    if (k > n) return BigInt(0);
    if (k < 1 || n < 1) return BigInt(0);
    return (factorial(n) * factorial(n - 1)) / (factorial(k) * factorial(k - 1)) / factorial(n - k);
}

auto max(R)(R r) if (isInputRange!R) {
    alias T = ElementType!R;
    T v = T.init;

    while (!r.empty) {
        if (v < r.front) {
            v = r.front;
        }
        r.popFront;
    }

    return v;
}

void main() {
    writeln("Unsigned Lah numbers: L(n, k):");
    write("n/k ");
    foreach (i; 0..13) {
        writef("%10d ", i);
    }
    writeln();
    foreach (row; 0..13) {
        writef("%-3d", row);
        foreach (i; 0..row+1) {
            auto l = lah(BigInt(row), BigInt(i));
            writef("%11d", l);
        }
        writeln();
    }
    writeln("\nMaximum value from the L(100, *) row:");
    auto lambda = (int a) => lah(BigInt(100), BigInt(a));
    writeln(iota(0, 100).map!lambda.max);
}


  

You may also check:How to resolve the algorithm Execute Brain step by step in the PHP programming language
You may also check:How to resolve the algorithm Topswops step by step in the Ruby programming language
You may also check:How to resolve the algorithm Determine if a string is collapsible step by step in the sed programming language
You may also check:How to resolve the algorithm Sierpinski triangle step by step in the ALGOL W programming language
You may also check:How to resolve the algorithm Odd word problem step by step in the M2000 Interpreter programming language