用c语言写一个代码,输出m到n间的全部素数,每个输出字宽为5个字符,每5个素数换一行
时间: 2024-05-06 17:20:33 浏览: 11
```c
#include <stdio.h>
int isPrime(int n) {
int i;
if (n == 2) return 1;
if (n < 2 || n % 2 == 0) return 0;
for (i = 3; i * i <= n; i += 2) {
if (n % i == 0) return 0;
}
return 1;
}
int main() {
int m, n, count = 0;
printf("请输入 m 和 n(m < n):");
scanf("%d%d", &m, &n);
for (int i = m; i <= n; i++) {
if (isPrime(i)) {
printf("%-5d", i);
count++;
if (count % 5 == 0) printf("\n");
}
}
if (count % 5 != 0) printf("\n");
return 0;
}
```
相关问题
输出1~n之间的所有素数,每行输出5个,用转义字符‘\t’对齐c语言代码
以下是输出1~n之间的所有素数的C语言代码:
```c
#include <stdio.h>
int is_prime(int n) {
if (n <= 1) {
return 0;
}
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int n;
printf("请输入n的值:");
scanf("%d", &n);
printf("1~%d之间的素数为:\n", n);
int count = 0;
for (int i = 2; i <= n; i++) {
if (is_prime(i)) {
printf("%d\t", i);
count++;
if (count % 5 == 0) {
printf("\n");
}
}
}
printf("\n");
return 0;
}
```
每行输出5个素数,用转义字符‘\t’对齐。
C语言 输出1~n之间的所有素数,每行输出5个,用转义字符‘\t’对齐
以下是C语言的代码实现:
```c
#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 main() {
int n, count = 0;
printf("请输入一个正整数n:");
scanf("%d", &n);
for (int i = 2; i <= n; i++) {
if (isPrime(i)) {
count++;
printf("%d\t", i);
if (count % 5 == 0) {
printf("\n");
}
}
}
return 0;
}
```
代码中的 `isPrime()` 函数用于判断一个数是否为素数。主函数中,我们先输入一个正整数n,然后遍历从2到n的每一个数,判断是否为素数,如果是素数,则输出并统计个数,每输出5个素数就换行。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.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_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)