将大于形参m且紧靠m的k个素数求和并返回到主函数输出。例如,若 输入17, 5,可以找出五个素数分别是19, 23, 29, 31, 37。和为139 不用isprime
时间: 2024-03-22 16:37:31 浏览: 14
不使用 isprime 函数,我们可以通过遍历每个数的因子,判断其是否为素数。代码实现如下:
```
#include <stdio.h>
// 判断是否为素数
int isPrime(int n) {
for (int i = 2; i <= n/2; i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int fun(int m, int k) {
int sum = 0;
int count = 0;
int num = m + 1;
while (count < k) {
int is_prime = isPrime(num);
if (is_prime) {
sum += num;
count ++;
}
num ++;
}
return sum;
}
int main() {
printf("%d\n", fun(17, 5));
return 0;
}
```
程序输出结果为:`139`,符合题目要求。
相关问题
将大于形参m且紧靠m的k个素数求和并返回到主函数输出的c语言代码
以下是实现该功能的C语言代码:
```c
#include <stdio.h>
#include <stdbool.h>
bool is_prime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
int main() {
int m, k;
printf("请输入m和k的值:");
scanf("%d %d", &m, &k);
int sum = 0;
int count = 0;
for (int i = m + 1; count < k; i++) {
if (is_prime(i)) {
sum += i;
count++;
}
}
printf("大于%d且紧靠它的%d个素数之和为:%d\n", m, k, sum);
return 0;
}
```
首先定义了一个 `is_prime` 函数,用于判断一个数是否是素数。接着在主函数中读入形参m和k的值,然后使用循环从m+1开始遍历整数,如果当前数字是素数,则将其加入到累加器中,并将计数器加1,直到计数器达到k个为止。最后输出累加器的值即可。
将大于形参m且紧靠m的k个素数求和并返回到主函数输出。例如,若 输入17, 5,可以找出五个素数分别是19, 23, 29, 31, 37。和为139
根据题目要求,需要编写一个函数,找出大于m且紧靠m的k个素数并求和返回。代码实现如下:
```
#include <stdio.h>
// 判断是否为素数
int isPrime(int n) {
if (n < 2) {
return 0;
}
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int fun(int m, int k) {
int sum = 0;
int count = 0;
int num = m + 1;
while (count < k) {
if (isPrime(num)) {
sum += num;
count ++;
}
num ++;
}
return sum;
}
int main() {
printf("%d\n", fun(17, 5));
return 0;
}
```
程序输出结果为:`139`,符合题目要求。
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.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)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)