用import math求[m,n] 范围内的全部素数并输出。m、n是键盘输入的正整数,如果m、n有0及负整数,则输出“输入不是正整数!如果范围内有素数,则输出素数,若无素数,则输出“不存在素数!”
时间: 2023-05-12 13:03:22 浏览: 52
以下是代码实现:
```
m = int(input("请输入m:"))
n = int(input("请输入n:"))
if m <= 0 or n <= 0:
print("输入不是正整数!")
else:
prime_list = []
for num in range(m, n+1):
if num > 1:
for i in range(2, int(num/2)+1):
if (num % i) == 0:
break
else:
prime_list.append(num)
if len(prime_list) > 0:
print(prime_list)
else:
print("不存在素数!")
```
如果输入的m、n都是正整数,则会输出[m,n]范围内的所有素数。如果范围内没有素数,则会输出“不存在素数!”
相关问题
Java从键盘输入一个正整数n,计算并输出n以内的全部素数。
好的,以下是Java的实现方式:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入一个正整数n:");
int n = sc.nextInt();
// 判断是否为素数的方法
boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
// 输出n以内的素数
for (int i = 2; i <= n; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
}
}
```
您可以将此代码复制到Java环境中运行,输入一个正整数n,即可得到n以内的所有素数。
输入正整数m和 k,输出从m开始的k个素数
以下是Python实现输入正整数m和k,输出从m开始的k个素数的代码:
```python
import math
def is_prime(num):
"""
判断一个数是否为素数
"""
if num < 2:
return False
for i in range(2, int(math.sqrt(num))+1):
if num % i == 0:
return False
return True
m = int(input("请输入正整数m:"))
k = int(input("请输入要输出的素数个数k:"))
count = 0
num = m
while count < k:
if is_prime(num):
print(num, end=' ')
count += 1
num += 1
```
输入正整数m和k后,程序会从m开始依次判断每个数是否为素数,如果是素数则输出,并计数器加1,直到输出了k个素数为止。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)