Last active
May 25, 2024 10:20
-
-
Save dacr/cfb8b02f36758e38158da25887733bc4 to your computer and use it in GitHub Desktop.
almost no size limit fact compute / published by https://github.com/dacr/code-examples-manager #0eba7267-0982-4f39-bb40-3c3b1e723336/a1b386c5638de9a80566278cb481234c6aa1aede
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// summary : almost no size limit fact compute | |
// keywords : scala, math, fact, @testable | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// id : 0eba7267-0982-4f39-bb40-3c3b1e723336 | |
// created-on : 2020-12-14T05:51:15Z | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : scala-cli $file | |
// --------------------- | |
//> using scala "3.4.2" | |
//> using dep "org.scalatest::scalatest:3.2.16" | |
//> using objectWrapper | |
// --------------------- | |
import org.scalatest.* | |
import flatspec.* | |
import matchers.* | |
import scala.annotation.tailrec | |
@tailrec | |
def fact(x: Int, accu: BigInt = 1): BigInt = | |
if (x <= 1) accu else fact(x - 1, accu * x) | |
def factClassic(n: BigInt): BigInt = | |
if (n <= 1) 1 else n*factClassic(n - 1) | |
def factAlt(num: Int): BigInt = { | |
LazyList | |
.from(1) | |
.take(num) | |
.map(x => BigInt(x)) | |
.foldLeft(BigInt(1)) {case (a,b) => a * b} | |
} | |
class FactTest extends AnyFlatSpec with should.Matchers { | |
override def suiteName: String = "FactTest" | |
"fact" should "return the right result" in { | |
fact(0) shouldBe 1 | |
fact(1) shouldBe 1 | |
fact(2) shouldBe 2 | |
fact(3) shouldBe 6 | |
fact(4) shouldBe 24 | |
fact(42) shouldBe BigInt("1405006117752879898543142606244511569936384000000000") | |
} | |
} | |
org.scalatest.tools.Runner.main(Array("-oDF", "-s", classOf[FactTest].getName)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment