C++输入一个正整数N,用to do输出N以内的所有质数
时间: 2024-09-07 21:01:08 浏览: 50
在C++中,你可以使用埃拉托斯特尼筛法(Sieve of Eratosthenes)来找出给定范围内(包括N本身)的所有质数。这里是一个简单的示例程序:
```cpp
#include <iostream>
#include <vector>
// Function to find prime numbers up to N
std::vector<int> sieveOfEratosthenes(int N) {
std::vector<bool> isPrime(N+1, true); // Initialize all numbers as prime
isPrime[0] = false; // 0 and 1 are not primes
isPrime[1] = false;
for (int i = 2; i * i <= N; ++i) {
if (isPrime[i]) {
for (int j = i * i; j <= N; j += i) {
isPrime[j] = false; // Mark multiples of i as composite
}
}
}
// Collect the prime numbers in a vector
std::vector<int> primes;
for (int i = 2; i <= N; ++i)
if (isPrime[i])
primes.push_back(i);
return primes;
}
int main() {
int N;
std::cout << "Enter a positive integer N: ";
std::cin >> N;
std::vector<int> primeNumbers = sieveOfEratosthenes(N);
// Output the prime numbers
for (int prime : primeNumbers) {
std::cout << prime << " ";
}
std::cout << "\n";
return 0;
}
```
当你运行这个程序并输入一个正整数N,它会打印出N范围内的所有质数。
阅读全文