How to resolve the algorithm Left factorials step by step in the Scala programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Left factorials step by step in the Scala programming language

Table of Contents

Problem Statement

Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:

(It may not be visually obvious, but the last example uses an upside-down exclamation mark.)

This Rosetta Code task will be using this formula   (factorial sums)   for   left factorial:

Display the left factorials for:

Display the length (in decimal digits) of the left factorials for:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Left factorials step by step in the Scala programming language

Source code in the scala programming language

object LeftFactorial extends App {

  // this part isn't really necessary, it just shows off Scala's ability
  // to match the mathematical syntax: !n
  implicit class RichInt(n:Int) {
    def unary_!() = factorial.take(n).sum
  }

  val factorial: Stream[BigInt] = 1 #:: factorial.zip(Stream.from(1)).map(n => n._2 * factorial(n._2 - 1))

  for (n <- (0 to 10) ++
            (20 to 110 by 10);
       value = !n) {
    println(s"!${n} = ${value}")
  }
  for (n <- 1000 to 10000 by 1000;
       length = (!n).toString.length) {
    println(s"length !${n} = ${length}")
  }
}


  

You may also check:How to resolve the algorithm Hello world/Line printer step by step in the Slope programming language
You may also check:How to resolve the algorithm Sum and product of an array step by step in the Pascal programming language
You may also check:How to resolve the algorithm Cullen and Woodall numbers step by step in the Verilog programming language
You may also check:How to resolve the algorithm Substring/Top and tail step by step in the Forth programming language
You may also check:How to resolve the algorithm Stack traces step by step in the Icon and Unicon programming language