Last active
December 19, 2018 18:12
-
-
Save xadrijo/2ef56d73b9c531b2660807e475f9772d to your computer and use it in GitHub Desktop.
Calculate Least Common Multiple and Greatest Common Factor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// Greatest common divisor | |
func main() { | |
a := []int32{2, 4} | |
b := []int32{16, 32, 96} | |
// Pendiente | |
//a := []int32{100, 99, 98, 97, 96, 95, 94, 93, 92, 91} | |
//b := []int32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} | |
println(getTotalX(a, b)) | |
} | |
func getTotalX(a []int32, b []int32) int32 { | |
var min = lcmMult(a) | |
var max = gcdMult(b) | |
var count int32 | |
for i := min; i <= max; i++ { | |
if max%i == 0 { | |
count++ | |
} | |
} | |
return int32(count) | |
} | |
// Euclidean algorithm | |
func gcd(a int32, b int32) int32 { | |
for b > 0 { | |
temp := b | |
b = a % b | |
a = temp | |
} | |
return a | |
} | |
func gcdMult(arr []int32) int32 { | |
var result = arr[0] | |
for _, num := range arr { | |
result = gcd(result, num) | |
} | |
println("max:", result) | |
return result | |
} | |
func lcm(a int32, b int32) int32 { | |
return a * (b / gcd(a, b)) | |
} | |
func lcmMult(arr []int32) int32 { | |
var result = arr[0] | |
for _, num := range arr { | |
result = lcm(result, num) | |
} | |
println("min:", result) | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment