【发布时间】:2018-07-23 09:23:22
【问题描述】:
我是 python 新手,我想知道如何创建一个函数,你可以在其中输入一个数字,它会为你提供数字素数。
示例:如果我输入 6,它会返回 13。因为 13 是第 6 个素数。
最好没有模块,除了标准库中的模块, 谢谢
【问题讨论】:
-
您有问题吗?
-
我该怎么做..?
我是 python 新手,我想知道如何创建一个函数,你可以在其中输入一个数字,它会为你提供数字素数。
示例:如果我输入 6,它会返回 13。因为 13 是第 6 个素数。
最好没有模块,除了标准库中的模块, 谢谢
【问题讨论】:
这就是你要找的:
def nth_prime_number(n):
# initial prime number list
prime_list = [2]
# first number to test if prime
num = 3
# keep generating primes until we get to the nth one
while len(prime_list) < n:
# check if num is divisible by any prime before it
for p in prime_list:
# if there is no remainder dividing the number
# then the number is not a prime
if num % p == 0:
# break to stop testing more numbers, we know it's not a prime
break
# if it is a prime, then add it to the list
# after a for loop, else runs if the "break" command has not been given
else:
# append to prime list
prime_list.append(num)
# same optimization you had, don't check even numbers
num += 2
# return the last prime number generated
return prime_list[-1]
x = nth_prime_number(8)
print(x)
【讨论】: