⑴ 用c语言编写函数int rev_prime(int m,int n,int x[]),求区间m到n中的所有整数的反序数,将反序数中的素数存入数组x中,函数的返回值是素数的个数。 反序数:将原数各位数字颠倒后的数,例如:123的反序数为321,70的反序数为7。 ⑵ 编写main函数,接收从键盘输入的m和n的值,调用函数reverse求m到n之间的所有元素的反序数中的素数,将结果数组按以下要求写到输出文件“out.txt”中。
时间: 2024-02-03 14:12:55 浏览: 35
以下是实现该功能的代码:
```
#include <stdio.h>
#include <math.h>
/* 判断一个数是否为素数 */
int is_prime(int n){
int i;
if(n < 2) return 0;
for(i = 2; i <= sqrt(n); i++){
if(n % i == 0) return 0;
}
return 1;
}
/* 反转一个整数 */
int reverse(int n){
int rev = 0;
while(n > 0){
rev = rev * 10 + n % 10;
n /= 10;
}
return rev;
}
/* 求区间m到n中所有整数的反序数中的素数 */
int rev_prime(int m, int n, int x[]){
int i, count = 0;
for(i = m; i <= n; i++){
int rev = reverse(i);
if(is_prime(rev)){
x[count] = rev;
count++;
}
}
return count;
}
int main(){
int m, n, x[100], i, count;
printf("请输入m和n的值:");
scanf("%d%d", &m, &n);
count = rev_prime(m, n, x);
FILE *fp;
fp = fopen("out.txt", "w");
fprintf(fp, "区间[%d, %d]中反序数中的素数有:%d个\n", m, n, count);
fprintf(fp, "分别是:");
for(i = 0; i < count; i++){
fprintf(fp, "%d ", x[i]);
}
fclose(fp);
printf("结果已写入文件out.txt中!\n");
return 0;
}
```
运行程序后,输入m和n的值,程序将在区间[m, n]中求出所有整数的反序数中的素数,并将结果写入out.txt文件中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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_column_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)