请编写函数fun,其功能是:将所有大于1小于整数m的非素数存入 xx所指数组中,非素数的个数通过k传回。 例如,若输入:17,则应输出:4689 10 12 14 15 16。
时间: 2023-03-28 22:03:05 浏览: 211
void fun(int m, int *x, int &k){
k = ;
for(int i=2; i<m; i++){
bool isPrime = true;
for(int j=2; j<i; j++){
if(i%j == ){
isPrime = false;
break;
}
}
if(!isPrime){
x[k++] = i;
}
}
}
//调用方式
int x[100], k;
fun(17, x, k);
for(int i=; i<k; i++){
cout << x[i] << " ";
}
cout << endl;
//输出结果:4 6 8 9 10 12 14 15 16
相关问题
请编写函数fun,其功能是: 将所有大于1小于整数m的非素数存入xx所指数组中, 非素数的个数通过k传回。
```
#include <stdio.h>
#include <math.h>
void fun(int m, int *xx, int *k)
{
int count = 0; // 计数器,记录非素数的个数
int i, j;
for(i = 2; i < m; i++)
{
for(j = 2; j <= sqrt(i); j++)
{
if(i % j == 0) // i不是素数
{
xx[count] = i; // 将i存入数组xx中
count++; // 非素数个数加1
break; // 跳出循环,i不需要再进行判断
}
}
}
*k = count; // 将非素数个数传回
}
int main()
{
int m = 20;
int xx[100] = {0}; // 初始化数组
int k; // 非素数个数
fun(m, xx, &k);
printf("非素数个数为:%d\n", k);
int i;
for(i = 0; i < k; i++)
{
printf("%d ", xx[i]);
}
printf("\n");
return 0;
}
```
c语言实现请编写函数fun,其功能是: 将所有大于1小于整数m的非素数存入xx所指数组中, 非素数的个数通过k传回
以下是一种可能的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int is_prime(int n) {
if (n <= 1) return 0;
int i;
for (i = 2; i <= sqrt(n); i++) {
if (n % i == 0) return 0;
}
return 1;
}
void fun(int m, int *xx, int *k) {
int i, j;
*k = 0;
for (i = 2; i < m; i++) {
if (!is_prime(i)) {
xx[(*k)++] = i;
}
}
}
int main() {
int m = 20;
int xx[100];
int k;
fun(m, xx, &k);
int i;
for (i = 0; i < k; i++) {
printf("%d ", xx[i]);
}
printf("\n");
return 0;
}
```
首先定义一个辅助函数 `is_prime` 判断一个整数是否为素数。然后在主函数中调用 `fun` 函数,传入整数 m、数组 xx 和指向变量 k 的指针。在 `fun` 函数中,首先将 k 设为 0,然后遍历 2 到 m-1 的整数,如果该整数不是素数,则存入 xx 数组中,同时将 k 的值加 1。最后返回时,k 的值即为非素数的个数。在主函数中打印出 xx 数组中的所有元素,即为所有大于 1 小于 m 的非素数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.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)