標籤:

*吧上有海外留學生問全部用遞歸求第N個質數,不能用循環

特別聲明:求質數有埃拉托斯特尼篩法等高級演算法,下面是用的試除法。

習題定義了2個函數,還規定了求質數的演算法,請看黃哥寫的python代碼和golang代碼。

點擊黃哥python培訓試看視頻播放地址

黃哥python遠程視頻培訓班

#coding:utf-8nimport mathn"""n黃哥python北京周末培訓班nhttps://github.com/pythonpeixun/article/blob/master/beijing_weekend.mdn黃哥python遠程視頻培訓nhttps://github.com/pythonpeixun/article/blob/master/index.mdn諮詢:qq:1465376564 黃哥python培訓nn"""ndef check_pr(a, b):n """傳2個參數, a 和 b=sqrt(a),求a是不是質數"""n if b < 2 and a > 1:n return Truen elif a % b == 0:n return Falsen else:n return check_pr(a, b-1)nndef nth_prime(n):n """用遞歸替代循環求第n個質數(從2起)。"""n count = 0n def helper(i=1):n nonlocal countn if check_pr(i, int(math.sqrt(i))):n count += 1n if count == n:n return in return helper(i+1)nn return helpernnif __name__ == __main__:n n = 100n print(nth_prime(n)())n

下面是golang實現

package mainnnimport (n "fmt"n "math"n)nn// 求質數的函數nfunc isPrime(a int, b float64) bool {n if b < 2 && a > 1 {n return truen } else if a%int(b) == 0 {n return falsen } else {n return isPrime(a, b-1)n }n}nn// 求第N個質數nfunc nPrime(n int) int {n count := 0n var helper func(i int) intn helper = func(i int) int {n if isPrime(i, math.Sqrt(float64(i))) {n count += 1n if count == n {n return in }nn }n return helper(i + 1)nn }n return helper(1)n}nnfunc main() {n n := 100n fmt.Println(nPrime(n))nn}n

推薦閱讀:

python Web 運維 爬蟲.....一條龍學習視頻教程
《Django By Example》第一章 中文翻譯
10min手寫(b六):b面試題解析丨Python實現多連接下載器

TAG:Python |