github.com/balzaczyy/golucene@v0.0.0-20151210033525-d0be9ee89713/core/util/math.go (about) 1 package util 2 3 import ( 4 "math" 5 ) 6 7 // util/MathUtil.java 8 9 /* Returns x <= 0 ? 0 : floor(log(x) ? log(base)) */ 10 func Log(x int64, base int) int { 11 assert2(base > 1, "base must be > 1") 12 ret := 0 13 for x >= int64(base) { 14 x /= int64(base) 15 ret++ 16 } 17 return ret 18 } 19 20 /* 21 Return the greatest common divisor of a and b, consistently with 22 big.GCD(a, b). 23 24 NOTE: A greatest common divisor must be positive, but 2^64 cannot be 25 expressed as an int64 although it is the GCD of math.MinInt64 and 0 26 and the GCD of math.MinInt64 and math.MinInt64. So in these 2 cases, 27 and only them, this method will return math.MinInt64. 28 */ 29 func Gcd(a, b int64) int64 { 30 if a < 0 { 31 a = -a 32 } 33 if b < 0 { 34 b = -b 35 } 36 if a == 0 { 37 return b 38 } else if b == 0 { 39 return a 40 } 41 commonTrailingZeros := NumberOfTrailingZeros(a | b) 42 a = int64(uint64(a) >> NumberOfTrailingZeros(a)) 43 for { 44 b = int64(uint64(b) >> NumberOfTrailingZeros(b)) 45 if a == b { 46 break 47 } 48 if a > b || a == math.MinInt64 { // math.MinInt64 is treated as 2^64 49 a, b = b, a 50 } 51 if a == 1 { 52 break 53 } 54 b -= a 55 } 56 return a << commonTrailingZeros 57 } 58 59 func NumberOfTrailingZeros(n int64) uint { 60 if n == 0 { 61 return 64 62 } 63 ans := 0 64 for { 65 if n&1 != 0 { 66 break 67 } 68 n >>= 1 69 ans++ 70 } 71 return uint(ans) 72 }