题目
By listing the first six prime numbers: 2,3,5,7,11, and 13, we can see that the 6th prime is 13.
What is the 10001st prime number?
解答
这道题首先就是写个函数判断质数,然后就是对着奇数来判断是不是质数,计数,找到第10001个质数。
import math
def is_prime(x):
if (x < 2):
return False
if (x == 2):
return True
for i in range(2, int(math.sqrt(x)+1)):
if (x % i == 0):
return False
return True
def solution7(N):
cnt = 2
num = 3
while cnt != N:
num += 2
if (is_prime(num)):
cnt += 1
return(num)
solution7(10001)
一回车马上出结果:

这是一个个算的,还可以来个初始化向量,把小数的倍数全部干掉,就可以得到一个质数列表。当然这里的问题就是向量要多大,这个得估计。对于质数,是有个估计的方法的。
n <- 10001
u <- ceiling(n * log(n) + n*log(log(n)))
x <- rep(TRUE, u)
for (i in seq(2, ceiling(sqrt(u)))) {
x[seq(2, u %/% i) * i] <- FALSE
}
primes <- which(x)[-1]
primes[n]
像这样的代码,就得用R来写,用Python写起来太麻烦。算个log,还得import math然后用math.log。矩阵用numpy也没有这个爽。
