如何在 Golang 中使用遞迴查詢兩個給定數字的最大公約數 (GCD)?
在本教程中,我們將瞭解如何使用 Golang 語言和遞迴來查詢兩個數字的最大公約數。我們將看到兩種使用遞迴查詢兩個數字 GCD 的方法。第一種方法需要更多時間,我們透過將兩個數字中的較小者減 1,然後檢查這兩個數字是否都可被該最小數整除。第二種方法需要更少的時間,我們透過將較大的數字減去較小的數字,直到兩個數字相等。
演算法
步驟 1 - 宣告變數來儲存兩個數字和答案。
步驟 2 - 初始化變數。
步驟 3 - 呼叫函式以使用將減少每次函式呼叫的最小數字查詢 GCD,對兩個數字進行取模運算,並在模為零時返回。
步驟 4 - 列印結果。
方法 1:使用遞迴函式的非高效方法。
在此示例中,我們透過將兩個數字中的較小者減 1,然後檢查這兩個數字是否都可被該最小數整除。
示例
package main
// fmt package provides the function to print anything
import (
"fmt"
)
// this function finds 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 be divided by 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, answer, minNumber int
// initializing both the variables
number1 = 20
number2 = 15
fmt.Println("Program to find the GCD of two numbers using the recursion function.")
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
answer = gcdOfTwoNumbers(number1, number2, minNumber)
// printing the result
fmt.Println("The GCD of", number1, "and", number2, "is", answer)
}
輸出
Program to find the GCD of two numbers using the recursion function. The GCD of 20 and 15 is 5
方法 2:使用遞迴函式的高效方法
在此示例中,我們將透過將較大的數字減去較小的數字,直到兩個數字相等,從而節省時間。
示例
package main
// fmt package provides the function to print anything
import (
"fmt"
)
// this function finds the GCD of two numbers with two parameters
// of int type and have a return type of int type
func gcdOfTwoNumbers(number1, number2 int) int {
// returning if both the numbers become equal
if number1 == number2 {
return number1
}
// reducing the lesser one with the greater one
if number1 > number2 {
number1 -= number2
} else {
number2 -= number1
}
// calling the function
return gcdOfTwoNumbers(number1, number2)
}
func main() {
// declaring the variable to store the value of two numbers
// and a variable to store an answer
var number1, number2, answer int
// initializing both the variables
number1 = 20
number2 = 15
fmt.Println("Program to find the GCD of two numbers in efficient way using the recursion function.")
// calling a function to find the GCD of two number
answer = gcdOfTwoNumbers(number1, number2)
// printing the result
fmt.Println("The GCD of", number1, "and", number2, "is", answer)
}
輸出
Program to find the GCD of two numbers in an efficient way using the recursion function. The GCD of 20 and 15 is 5
結論
這些是使用遞迴查詢兩個數字 GCD 的不同方法。第二種方法比第一種方法更有效。要了解更多關於 go 的資訊,您可以瀏覽這些教程。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP