Last active
February 3, 2026 20:26
-
-
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/9f5679ca66af5ecc33b1f712e14bdfbb45502ba5
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 License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // 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