如何使用 Go 語言中的遞迴查詢兩個給定數字的最小公倍數?


在本教程中,我們將使用遞迴在 Go 語言中查詢兩個數字的最小公倍數。為了遞迴地找到最小公倍數,我們將使用最小公倍數與兩個數字的最大公約數(GCD)之間的關係。最小公倍數是指能被兩個數字整除的最小數字。

例如,

假設這兩個數字是 10 和 4。能被這兩個數字整除的最小數字是 20。

使用最小公倍數和最大公約數之間的關係查詢最小公倍數

在本例中,我們將使用最小公倍數和兩個數字的最大公約數之間的關係來查詢最小公倍數。

解釋

The relationship between LCM and GCD is
LCM = (number1 * number2) / GCD
number1 = 20
Number2 = 15
GCD = 5
LCM = ( 20 * 15 ) / 5
   = 300 / 5
   = 60

演算法

  • 步驟 1 - var number1, number2, gcd, minNumber int - 在這行程式碼中,我們聲明瞭兩個變數來儲存我們需要找到最小公倍數的數字,一個變數來儲存這兩個數字的最大公約數,以及一個變數來儲存這兩個數字中的最小值。

  • 步驟 2 - number1 = 20 number2 = 15 - 使用您想要查詢最小公倍數的值初始化這兩個數字。

  • 步驟 3 - if number1 < number2 { } - 查詢數字中的最小值並將其儲存在 minNumber 變數中。

  • 步驟 4 - gcdOfTwoNumbers(number1, number2, minNumber) - 呼叫遞迴函式以查詢這兩個數字的最大公約數。

  • 步驟 5 - LCM:= (number1 * number2) / gcd - 使用最大公約數和最小公倍數的關係查詢最小公倍數。

示例

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

描述

在這種方法中,我們首先找到最小數字,然後使用遞迴方法找到這兩個數字的最大公約數,然後透過應用最大公約數和最小公倍數的關係來找到最小公倍數。

結論

這是使用 Go 語言中與最大公約數相關的關係查詢兩個數字的最小公倍數的遞迴方法。這是查詢最小公倍數的有效方法之一。要了解更多關於 Go 的資訊,您可以瀏覽這些教程。

更新於: 2023年1月11日

585 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告