How to resolve the algorithm Factorial step by step in the Zig programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Factorial step by step in the Zig 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 Zig programming language

Source code in the zig programming language

const stdout = @import("std").io.getStdOut().outStream();

pub fn factorial(comptime Num: type, n: i8) ?Num {
    return if (@typeInfo(Num) != .Int)
        @compileError("factorial called with num-integral type: " ++ @typeName(Num))
    else if (n < 0)
        null
    else calc: {
        var i: i8 = 1;
        var fac: Num = 1;
        while (i <= n) : (i += 1) {
            if (@mulWithOverflow(Num, fac, i, &fac))
                break :calc null;
        } else break :calc fac;
    };
}

pub fn main() !void {
    try stdout.print("-1! = {}\n", .{factorial(i32, -1)});
    try stdout.print("0! = {}\n", .{factorial(i32, 0)});
    try stdout.print("5! = {}\n", .{factorial(i32, 5)});
    try stdout.print("33!(64 bit) = {}\n", .{factorial(i64, 33)}); // not vailid i64 factorial
    try stdout.print("33! = {}\n", .{factorial(i128, 33)}); // biggest facorial possible
    try stdout.print("34! = {}\n", .{factorial(i128, 34)}); // will overflow
}

  

You may also check:How to resolve the algorithm Levenshtein distance step by step in the LFE programming language
You may also check:How to resolve the algorithm Ormiston triples step by step in the F# programming language
You may also check:How to resolve the algorithm Runge-Kutta method step by step in the Run BASIC programming language
You may also check:How to resolve the algorithm Yin and yang step by step in the UNIX Shell programming language
You may also check:How to resolve the algorithm Keyboard input/Obtain a Y or N response step by step in the Axe programming language