C++输出1到100间的素数
时间: 2023-05-17 09:07:55 浏览: 127
以下是 C++ 代码,用于输出 1 到 100 之间的素数:
```cpp
#include <iostream>
using namespace std;
bool isPrime(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() {
for (int i = 1; i <= 100; i++) {
if (isPrime(i)) {
cout << i << " ";
}
}
cout << endl;
return 0;
}
```
输出结果为:
```
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
```
相关问题
C++输出1-100的素数
以下是 C++ 代码,输出了 1 到 100 之间的所有素数:
#include <iostream>
using namespace std;
bool is_prime(int num) {
if(num <= 1) {
return false;
}
for(int i = 2; i * i <= num; i++) {
if(num % i == 0) {
return false;
}
}
return true;
}
int main() {
for(int i = 1; i <= 100; i++) {
if(is_prime(i)) {
cout << i << " ";
}
}
return 0;
}
c++语言输出1-100的素数
在C++中,你可以使用循环和条件判断来找出并打印1到100之间的素数。素数是指只有两个正因数(1和它本身)的大于1的自然数。下面是一个简单的示例程序:
```cpp
#include <iostream>
bool isPrime(int num) {
if (num <= 1)
return false;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0)
return false;
}
return true;
}
void printPrimes(int start, int end) {
for (int i = start; i <= end; i++) {
if (isPrime(i))
std::cout << i << " ";
}
std::cout << "\n";
}
int main() {
printPrimes(1, 100);
return 0;
}
```
这个程序首先定义了一个辅助函数`isPrime()`用于检查一个数是否为素数,然后在`printPrimes()`函数中从1遍历到100,对每个数字调用`isPrime()`,如果是素数则打印出来。
阅读全文
相关推荐
![](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)