github.com/insolar/vanilla@v0.0.0-20201023172447-248fdf805322/args/math.go (about) 1 // Copyright 2020 Insolar Network Ltd. 2 // All rights reserved. 3 // This material is licensed under the Insolar License version 1.0, 4 // available at https://github.com/insolar/assured-ledger/blob/master/LICENSE.md. 5 6 package args 7 8 import "math/bits" 9 10 func GreatestCommonDivisor(a, b int) int { 11 if a == b { 12 return a 13 } 14 15 for b != 0 { 16 t := b 17 b = a % b 18 a = t 19 } 20 return a 21 } 22 23 func GreatestCommonDivisorUint64(a, b uint64) uint64 { 24 if a == b { 25 return a 26 } 27 28 for b != 0 { 29 t := b 30 b = a % b 31 a = t 32 } 33 return a 34 } 35 36 func GreatestCommonDivisorInt64(a, b int64) int64 { 37 if a == b { 38 return a 39 } 40 41 for b != 0 { 42 t := b 43 b = a % b 44 a = t 45 } 46 return a 47 } 48 49 func GCDListUint64(min, a uint64, b ...uint64) uint64 { 50 for _, bb := range b { 51 if a <= min || a <= 1 { 52 break 53 } 54 a = GreatestCommonDivisorUint64(a, bb) 55 } 56 return a 57 } 58 59 func GCDListInt64(min, a int64, b ...int64) int64 { 60 for _, bb := range b { 61 if a <= min || a <= 1 { 62 break 63 } 64 a = GreatestCommonDivisorInt64(a, bb) 65 } 66 return a 67 } 68 69 func GCDListInt(min, a int, b ...int) int { 70 for _, bb := range b { 71 if a <= min || a <= 1 { 72 break 73 } 74 a = GreatestCommonDivisor(a, bb) 75 } 76 return a 77 } 78 79 // IsPowerOfTwo also returns true for (0) 80 func IsPowerOfTwo(x uint) bool { 81 return x&(x-1) == 0 82 } 83 84 // CeilingPowerOfTwo returns 0 for (0) 85 func CeilingPowerOfTwo(x uint) uint { 86 if IsPowerOfTwo(x) { 87 return x 88 } 89 return 1 << uint(bits.Len(x)) 90 }