找1到N间的素数C++
时间: 2024-12-18 10:20:35 浏览: 5
在C++中,找到1到N之间的所有素数可以使用埃拉托斯特尼筛法(Sieve of Eratosthenes)。这是一种经典算法,通过维护一个布尔数组记录每个数字是否是素数。以下是简单的实现步骤:
```cpp
#include <iostream>
#include <vector>
using namespace std;
// Function to find all prime numbers up to N
void printPrimes(int N) {
vector<bool> isPrime(N+1, true); // Initialize all numbers as prime
isPrime[0] = isPrime[1] = false; // Zero and One are not primes
for (int i = 2; i*i <= N; i++) { // Check for factors up to sqrt(N)
if (isPrime[i]) {
for (int j = i * i; j <= N; j += i) // Mark multiples of i as composite
isPrime[j] = false;
}
}
// Print the prime numbers
for (int i = 2; i <= N; i++)
if (isPrime[i])
cout << i << " ";
}
int main() {
int N;
cout << "Enter a number: ";
cin >> N;
cout << "Prime numbers from 1 to " << N << " are:\n";
printPrimes(N);
return 0;
}
```
当你运行这个程序时,它会提示你输入一个数N,然后输出从1到N的所有素数。
阅读全文