2

I am trying to implement LCM in one line in Scala.

This is how I've implemented it with 2 functions:

def gcd(a: BigInt, b: BigInt):BigInt=if (b==0) a.abs else gcd(b, a%b)
def lcm(list: Seq[BigInt]):BigInt=list.foldLeft(BigInt(1))((a, b) => (a/gcd(a,b))*b)

How would you convert gcd into a lambda inside lcm?

jwvh
  • 50,871
  • 7
  • 38
  • 64
bartosz.lipinski
  • 2,627
  • 2
  • 21
  • 34
  • 1
    Without some sort of fix point operator (which I don't think already exists in the Scala libraries - you could define it, but then that's an extra line), I don't think you can do this. The problem is that you need `gcd` to be anonymous, but also recursive. – Alec Nov 29 '16 at 20:58
  • @Alec i'm curious to see an answer using fix points – soote Nov 29 '16 at 21:29

1 Answers1

2

You need a GCD calculation that isn't recursive.

def lcm(list: Seq[BigInt]):BigInt=list.foldLeft(1:BigInt){(a,b) => b*a / Stream.iterate((a,b)){case (x,y) => (y, x%y)}.dropWhile(_._2 != 0).head._1.abs}

(Here it is in a slightly more readable format.)

def lcm(list: Seq[BigInt]):BigInt=list.foldLeft(1:BigInt){
  (a, b) => b * a /
  Stream.iterate((a,b)){case (x,y) => (y, x%y)}.dropWhile(_._2 != 0).head._1.abs
}
jwvh
  • 50,871
  • 7
  • 38
  • 64