How to resolve the algorithm Factorial step by step in the D programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Factorial step by step in the D programming language
Table of Contents
Problem Statement
Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative n errors is optional.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Factorial step by step in the D programming language
Source code in the d programming language
uint factorial(in uint n) pure nothrow @nogc
in {
assert(n <= 12);
} body {
uint result = 1;
foreach (immutable i; 1 .. n + 1)
result *= i;
return result;
}
// Computed and printed at compile-time.
pragma(msg, 12.factorial);
void main() {
import std.stdio;
// Computed and printed at run-time.
12.factorial.writeln;
}
uint factorial(in uint n) pure nothrow @nogc
in {
assert(n <= 12);
} body {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}
// Computed and printed at compile-time.
pragma(msg, 12.factorial);
void main() {
import std.stdio;
// Computed and printed at run-time.
12.factorial.writeln;
}
import std.stdio, std.algorithm, std.range;
uint factorial(in uint n) pure nothrow @nogc
in {
assert(n <= 12);
} body {
return reduce!q{a * b}(1u, iota(1, n + 1));
}
// Computed and printed at compile-time.
pragma(msg, 12.factorial);
void main() {
// Computed and printed at run-time.
12.factorial.writeln;
}
uint factorial(in uint n) pure nothrow
in {
assert(n <= 12);
} body {
static uint inner(uint n, uint acc) pure nothrow @nogc {
if (n < 1)
return acc;
else
return inner(n - 1, acc * n);
}
return inner(n, 1);
}
// Computed and printed at compile-time.
pragma(msg, 12.factorial);
void main() {
import std.stdio;
// Computed and printed at run-time.
12.factorial.writeln;
}
You may also check:How to resolve the algorithm Zeckendorf number representation step by step in the Forth programming language
You may also check:How to resolve the algorithm Increment a numerical string step by step in the Emacs Lisp programming language
You may also check:How to resolve the algorithm Dutch national flag problem step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Horner's rule for polynomial evaluation step by step in the Sather programming language
You may also check:How to resolve the algorithm Bioinformatics/Sequence mutation step by step in the V (Vlang) programming language