Last active
May 25, 2024 10:18
-
-
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/fdac1e3b6d87558fe11496ff476d01d5553a121b
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 : lcm and gcd | |
// keywords : scala, math, lcm, gcd, cheatsheet, @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 : 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