输入正整数m和 k,输出从m开始的k个素数
时间: 2024-06-13 08:06:36 浏览: 18
以下是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个素数为止。
相关问题
用c语言输入正整数m和 k,输出从m开始的k个素数
以下是用C语言输入正整数m和k,输出从m开始的k个素数的代码实现:
```c
#include <stdio.h>
#include <math.h>
int prime(int x) // 判断一个数是否为素数的函数
{
int check = 1;
if (x == 1) {
check = 0;
} else {
for (int i = 2; i <= sqrt(x); i++) {
if (x % i == 0) {
check = 0;
break;
}
}
}
return check;
}
int main()
{
int m, k;
int count = 0, n = 0;
scanf("%d %d", &m, &k);
while (count < k) {
if (prime(m) == 1) {
printf("%d ", m);
count++;
}
m++;
}
return 0;
}
```
C语言,找出大于正整数m且靠近m的k个素数,m和k均从键盘输入
```c
#include <stdio.h>
#include <math.h>
int isPrime(int n) {
if (n <= 1) {
return 0;
}
int sqr = sqrt(n);
for (int i = 2; i <= sqr; i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int m, k;
printf("请输入正整数m和k:");
scanf("%d %d", &m, &k);
int count = 0;
int num = m + 1;
while (count < k) {
if (isPrime(num)) {
printf("%d ", num);
count++;
}
num++;
}
return 0;
}
```
首先定义一个函数`isPrime`用于判断一个数是否为素数,如果是则返回1,否则返回0。接着从键盘读入正整数m和k,从m+1开始往后遍历每个整数,如果是素数则输出并计数器加1,直到找到k个素数为止。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)