辗转相除法(欧几里得算法)
两个正整数a和b(a>b),他们的最大公约数等于a除以b的余数c和b之间的最大公约数
func getGreatestCommonDivisor(a,b int) int {
big := 0
small := 0
if a > b {
big = a
small = b
}else {
big = b
small = a
}
if big % small == 0 {
return small
}
return getGreatestCommonDivisor(big%small,small)
}
github:https://github.com/whileW/algorihm-go/tree/master/greatest_common_divisor/euclidean_algorihm
------------------------------------------------------------------------------------------------------------------------------------------------------
更相减损数
两个正整数a和b(a>b),他们的最大公约数等于a-b的差值c和较小数b的最大公约数
func getGreatestCommonDivisor(a,b int) int {
if a == b {
return a
}
big := 0
small := 0
if a > b {
big = a
small = b
}else {
big = b
small = a
}
return getGreatestCommonDivisor(big-small,small)
}
github:https://github.com/whileW/algorihm-go/tree/master/greatest_common_divisor/more_phase_loss
------------------------------------------------------------------------------------------------------------------------------------------------------
gcd
当a和b均为偶数时,gcd(a,b) = 2gcd(a/2,b/2) = 2gcd(a>>1,b>>1)
当a为偶数,b为奇数时,gcd(a,b) = gcd(a/2,b) = gcd(a>>1,b)
当a为奇数,b为偶数时,gcd(a,b) = gcd(a,b/2) = gcd(a,b>>1)
当a,b均为奇数时,先利用更相减损术运算一次,gcd(a,b) = gcd(b,a-b),此时a-b必然是偶数
//a&1 == 0 说明a 为偶数,a&1 != 0 说明a为奇数
func gcd(a,b int) int {
if a == b {
return a
}
if a&1 == 0 && b&1 == 0 {
return gcd(a>>1,b>>1)<<1
}else if a&1 == 0 && b&1 != 0 {
return gcd(a>>1,b)
}else if a&1 != 0 && b&1 == 0 {
return gcd(a,b>>1)
}else {
big := 0
small := 0
if a > b {
big = a
small = b
}else {
big = b
small = a
}
return gcd(big-small,small)
}
}
github:https://github.com/whileW/algorihm-go/tree/master/greatest_common_divisor/gcd