我正在尝试在Scala的一行中实现LCM。
这就是我用2个函数实现它的方法:
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)
如何将gcd转换为lcm内的lambda?
答案 0 :(得分:1)
您需要一个不递归的GCD计算。
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}
(这里是略微更易读的格式。)
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
}