Last active
February 3, 2026 20:20
-
-
Save dacr/1ff865c9689d042a4b10c0e98fbc2a38 to your computer and use it in GitHub Desktop.
lcm and gcd / published by https://github.com/dacr/code-examples-manager #9695d0d2-0501-4967-bc2e-9c149e1da510/18a73e59e8f667e291d46d4a6795d765914e943f
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 : lcm and gcd | |
| // keywords : scala, math, lcm, gcd, cheatsheet, @testable | |
| // publish : gist | |
| // authors : David Crosson | |
| // license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // id : 9695d0d2-0501-4967-bc2e-9c149e1da510 | |
| // 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._, flatspec._, matchers._ | |
| def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a % b) | |
| def lcm(a: Long, b: Long): Long = if (a == 0 || b == 0) 0 else a * b / gcd(a, b) | |
| def gcds(nums: Iterable[Long]): Long = nums.reduce(gcd) | |
| def lcms(nums: Iterable[Long]): Long = nums.reduce(lcm) | |
| def gcds(nums: Long*): Long = nums.reduce(gcd) | |
| def lcms(nums: Long*): Long = nums.reduce(lcm) | |
| class FactTest extends AnyFlatSpec with should.Matchers { | |
| override def suiteName: String = "FactTest" | |
| "lcm" should "return the right result" in { | |
| lcms(60, 168) shouldBe 840 | |
| } | |
| "gcd" should "return the right result" in { | |
| gcds(36, 48, 60) shouldBe 12 | |
| } | |
| } | |
| 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