如何在Golang中用递归法找到两个给定数字的LCM
在本教程中,我们将使用递归法在Golang中找到两个数字的最小公倍数。为了找到LCM的递归,我们将使用LCM与两个数的最大公除数即GCD的关系。LCM代表最小公倍数,是能被两个数字整除的最小的数字。
比如说。
假设这两个数字是10和4。能被这两个数字平均分割的最小的数字是20。
在这个例子中,我们将利用两个数字的LCM和GCD之间的关系来寻找LCM。
The relationship between LCM and GCD is
LCM = (number1 * number2) / GCD
number1 = 20
Number2 = 15
GCD = 5
LCM = ( 20 * 15 ) / 5
= 300 / 5
= 60
第2步:number1 = 20 number2 = 15 – 用你想找到的LCM值来初始化这两个数字。
第3步- if number1 < number2 { } – 在数字中找到最小值并存储在minNumber变量中。
第4步- gcdOfTwoNumbers(number1, number2, minNumber) – 调用递归函数来寻找两个数字的GCD。
number2) / gcd – 利用GCD和LCM的关系寻找LCM。
package main
// fmt package provides the function to print anything
import (
"fmt"
)
// this function is finding the GCD of two numbers with three parameters
// of int type and have a return type of int type
func gcdOfTwoNumbers(number1, number2, minNumber int) int {
// checking if the number minNumber can divide both number1 and number2
if minNumber == 1 || (number1%minNumber == 0 && number2%minNumber == 0) {
return minNumber
}
// returning the GCD
return gcdOfTwoNumbers(number1, number2, minNumber-1)
}
func main() {
// declaring the variable to store the value of two numbers
// and a variable to store an answer
var number1, number2, gcd, minNumber int
// initializing both the variables
number1 = 20
number2 = 15
fmt.Println("Program to find the LCM of two numbers using the relation with GCD using recursion.")
if number1 < number2 {
minNumber = number1
} else {
minNumber = number2
}
// calling a function to find the GCD of two number
// and passing a minimum of number1 and number2
gcd = gcdOfTwoNumbers(number1, number2, minNumber)
LCM := (number1 * number2) / gcd
// printing the result
fmt.Println("The LCM of", number1, "and", number2, "is", LCM)
}
Program to find the LCM of two numbers using the relation with GCD using recursion.
The LCM of 20 and 15 is 60
在这种方法中,我们首先要找到最小的数字,然后递归地找到这两个数字的最大公除数,通过应用GCD和LCM关系找到LCM。
这是在Golang中使用与GCD有关的递归方法来寻找两个数字的LCM。这是寻找LCM的有效方法之一。要了解更多关于go的知识,你可以探索这些教程。