如何使用 Go 語言中的遞迴判斷給定數字是否為素數?


在數學中,有一些數字只能被 1 或自身整除,這些數字被稱為素數。例如,2、3、5、7 等。在程式設計中,我們可以建立一個程式來檢查一個數字是否為素數。在本文中,我們將使用遞迴的概念,即在函式中呼叫函式,來建立一個程式來檢查數字是否為素數。

示例 1

在這個例子中,我們將建立一個帶有兩個引數的遞迴函式,一個是數字,另一個是除數。數字是我們需要檢查是否為素數的數字,除數由數字 - 1 初始化。然後在每次函式呼叫中,我們將檢查數字 % 除數是否為 0,並減少除數的值。如果在任何時候數字可以被除數整除,那麼我們將返回 false,否則在最後除數達到 1 時返回 false。

演算法

  • 步驟 1:使用 import 關鍵字在頂部匯入所需的包。

  • 步驟 2:然後 main 函式將首先執行。

    • 首先,我們宣告 int 變數並初始化它。

    • 現在我們在建立一個 if 條件,在其中首先檢查數字是否為 1。如果不是,則透過傳遞數字和除數作為引數來呼叫 isPrime() 函式。

    • 根據 if 條件,我們列印結果。

  • 步驟 3

    • 在 isPrime() 函式中,我們有一個基本條件,即除數是否為零。

    • 然後我們找到一個餘數,它是否為零。

    • 然後我們透過將除數減少 1 來呼叫 isPrime() 函式。

示例

package main

import (
    // fmt package provides the function to print anything
    "fmt"
)

// declare the function with int type parameters and bool return type
func isPrime(number, divisor int) bool {
    // if the divisor reached 1 returning true
    if divisor == 1 {
        return true
    }
    // if the number is divisible by any number in between 1 and number them returning false
    if number%divisor == 0 {
        return false
    }

    // calling the function by reducing the divisor by 1
    return isPrime(number, divisor-1)
}
func main() {
    // declaring the number variable of the int type
    var number int

    fmt.Println("Golang program to find whether the number is prime or not using recursion.")

    // initializing the number that we want to check is prime or not
    number = 7

    // starting the if the condition that is checking that number is greater than 1 or not
    // also calling isPrime() number that is checking whether the number is prime or not
    // && is an operator in which if both the condition on the right and left are true then
    //Only we will go inside if block
    if number > 1 && isPrime(number, number-1) {
        fmt.Println("The number", number, "is a prime number.")
    } else {
        fmt.Println("The number", number, "is not a prime number.")
    }
}

輸出

Golang program to find whether the number is prime or not using recursion.
The number 7 is a prime number.

結論

這就是我們如何使用遞迴函式來判斷一個數字是否為素數。還有其他方法可以檢查數字是否為素數,例如迭代方法或使用篩法。由於我們建立了一個單獨的函式,因此可以說程式碼是可重用的。要了解更多關於 Go 語言的資訊,您可以瀏覽這些 教程

更新於:2023-07-10

191 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.