Skip to content

Commit 6760117

Browse files
committed
黄哥所写的python文章
1 parent de9a9f6 commit 6760117

1 file changed

Lines changed: 89 additions & 0 deletions

File tree

python/python_recursive_prime.md

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
#*吧上有海外留学生问全部用递归求第N个质数,不能用循环
2+
3+
## 习题定义了2个函数,还规定了求质数的算法,请看黄哥写的python代码和golang代码。
4+
5+
[点击黄哥python培训试看视频播放地址](https://github.com/pythonpeixun/article/blob/master/python_shiping.md)
6+
7+
[黄哥python远程视频培训班](https://github.com/pythonpeixun/article/blob/master/index.md)
8+
9+
10+
11+
#coding:utf-8
12+
import math
13+
"""
14+
黄哥python北京周末培训班
15+
https://github.com/pythonpeixun/article/blob/master/beijing_weekend.md
16+
黄哥python远程视频培训
17+
https://github.com/pythonpeixun/article/blob/master/index.md
18+
咨询:qq:1465376564 黄哥python培训
19+
20+
"""
21+
def check_pr(a, b):
22+
"""传2个参数, a 和 b=sqrt(a),求a是不是质数"""
23+
if b < 2 and a > 1:
24+
return True
25+
elif a % b == 0:
26+
return False
27+
else:
28+
return check_pr(a, b-1)
29+
30+
def nth_prime(n):
31+
"""用递归替代循环求第n个质数(从2起)。"""
32+
count = 0
33+
def helper(i=1):
34+
nonlocal count
35+
if check_pr(i, int(math.sqrt(i))):
36+
count += 1
37+
if count == n:
38+
return i
39+
return helper(i+1)
40+
41+
return helper
42+
43+
if __name__ == '__main__':
44+
n = 100
45+
print(nth_prime(n)())
46+
47+
##下面是golang实现
48+
49+
package main
50+
51+
import (
52+
"fmt"
53+
"math"
54+
)
55+
56+
// 求质数的函数
57+
func isPrime(a int, b float64) bool {
58+
if b < 2 && a > 1 {
59+
return true
60+
} else if a%int(b) == 0 {
61+
return false
62+
} else {
63+
return isPrime(a, b-1)
64+
}
65+
}
66+
67+
// 求第N个质数
68+
func nPrime(n int) int {
69+
count := 0
70+
var helper func(i int) int
71+
helper = func(i int) int {
72+
if isPrime(i, math.Sqrt(float64(i))) {
73+
count += 1
74+
if count == n {
75+
return i
76+
}
77+
78+
}
79+
return helper(i + 1)
80+
81+
}
82+
return helper(1)
83+
}
84+
85+
func main() {
86+
n := 100
87+
fmt.Println(nPrime(n))
88+
89+
}

0 commit comments

Comments
 (0)