Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 27, 2023 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/1ff865c9689d042a4b10c0e98fbc2a38 to your computer and use it in GitHub Desktop.
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/e7075d18c335a23aaac8e83e981cf77b36c352b0
// 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.3.0"
//> 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