github.com/yandex/pandora@v0.5.32/lib/math/gcd_lcm.go (about)

     1  package math
     2  
     3  func GCD(a, b int64) int64 {
     4  	for a > 0 && b > 0 {
     5  		if a >= b {
     6  			a = a % b
     7  		} else {
     8  			b = b % a
     9  		}
    10  	}
    11  	if a > b {
    12  		return a
    13  	}
    14  	return b
    15  }
    16  
    17  func GCDM(weights ...int64) int64 {
    18  	l := len(weights)
    19  	if l < 2 {
    20  		return 0
    21  	}
    22  	res := GCD(weights[l-2], weights[l-1])
    23  	if l == 2 {
    24  		return res
    25  	}
    26  	return GCD(GCDM(weights[:l-1]...), res)
    27  }
    28  
    29  func LCM(a, b int64) int64 {
    30  	return (a * b) / GCD(a, b)
    31  }
    32  
    33  func LCMM(a ...int64) int64 {
    34  	l := len(a)
    35  	if l < 2 {
    36  		return 0
    37  	}
    38  	res := LCM(a[l-2], a[l-1])
    39  	if l == 2 {
    40  		return res
    41  	}
    42  	return LCM(LCMM(a[:l-1]...), res)
    43  }