c语言使用穷举法并分别用for、while、循环语句求出N~M之间的质数。
时间: 2024-04-09 12:29:02 浏览: 18
好的,我可以帮你解答这个问题。以下是使用穷举法分别使用for、while和do-while循环语句求出N~M之间的质数的C语言代码示例:
使用for循环:
```c
#include <stdio.h>
int isPrime(int num) {
if (num <= 1) {
return 0;
}
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
return 0;
}
}
return 1;
}
void findPrimes(int N, int M) {
printf("Prime numbers between %d and %d are:\n", N, M);
for (int i = N; i <= M; i++) {
if (isPrime(i)) {
printf("%d ", i);
}
}
printf("\n");
}
int main() {
int N, M;
printf("Enter the range (N and M): ");
scanf("%d %d", &N, &M);
findPrimes(N, M);
return 0;
}
```
使用while循环:
```c
#include <stdio.h>
int isPrime(int num) {
if (num <= 1) {
return 0;
}
int i = 2;
while (i <= num / 2) {
if (num % i == 0) {
return 0;
}
i++;
}
return 1;
}
void findPrimes(int N, int M) {
printf("Prime numbers between %d and %d are:\n", N, M);
int i = N;
while (i <= M) {
if (isPrime(i)) {
printf("%d ", i);
}
i++;
}
printf("\n");
}
int main() {
int N, M;
printf("Enter the range (N and M): ");
scanf("%d %d", &N, &M);
findPrimes(N, M);
return 0;
}
```
使用do-while循环:
```c
#include <stdio.h>
int isPrime(int num) {
if (num <= 1) {
return 0;
}
int i = 2;
do {
if (num % i == 0) {
return 0;
}
i++;
} while (i <= num / 2);
return 1;
}
void findPrimes(int N, int M) {
printf("Prime numbers between %d and %d are:\n", N, M);
int i = N;
do {
if (isPrime(i)) {
printf("%d ", i);
}
i++;
} while (i <= M);
printf("\n");
}
int main() {
int N, M;
printf("Enter the range (N and M): ");
scanf("%d %d", &N, &M);
findPrimes(N, M);
return 0;
}
```
这些代码会找出给定范围内的所有质数,并将它们打印出来。希望对你有帮助!如果有任何疑问,请随时提问。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)