Last active
May 27, 2023 06:28
-
-
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/a2f1c3892e82cab8467f42c2515ad5d0fc663e4f
This file contains 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.3.0" | |
//> 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