Python中,输入一个整数,求第n小的质数代码怎么写
时间: 2023-05-20 22:07:45 浏览: 100
以下是 Python 代码,用来求第 n 小的质数:
```python
def is_prime(num):
'''判断一个数是否为质数'''
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def nth_prime(n):
'''获取第 n 小的质数'''
count = 0
num = 2
while count < n:
if is_prime(num):
count += 1
num += 1
return num - 1
```
对于输入的整数 n,调用 nth_prime(n) 函数即可得到第 n 小的质数。
注意:如果质数范围较大,上面的代码可能会执行很慢。实际应用中,应该采用更高效的算法,例如 Sieve of Eratosthenes。
相关问题
Python:输入一个正整数n,求第n小的质数
可以使用一个函数is_prime(num)来判断一个数是否为质数,然后从2开始遍历自然数,直到找到第n个质数为止。
代码如下:
```python
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def nth_prime(n):
count = 0
num = 2
while True:
if is_prime(num):
count += 1
if count == n:
return num
num += 1
```
使用示例:
```python
print(nth_prime(1)) # 2
print(nth_prime(10)) # 29
print(nth_prime(100)) # 541
```
输入一个整数n,求第n小的质数
以下是Python代码实现:
```python
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def nth_prime(n):
count = 0
num = 2
while count < n:
if is_prime(num):
count += 1
num += 1
return num - 1
n = int(input("请输入一个整数:"))
print("第", n, "小的质数为:", nth_prime(n))
```
运行结果:
```
请输入一个整数:10
第 10 小的质数为: 29
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)