gpt-4-0314· OpenAI
Arena Human Preference 55K
Please implement a function in C++ that computes all primes up to a given input number,…
- User
Please implement a function in C++ that computes all primes up to a given input number, using the sieve of Eratosthenes.
- Assistant
Here's a C++ implementation of the Sieve of Eratosthenes algorithm to find all prime numbers up to a given input number:
#include <iostream> #include <vector> #include <cmath> std::vector<int> sieve_of_eratosthenes(int n) { std::vector<bool> is_prime(n + 1, true); std::vector<int> primes; is_prime[0] = false; is_prime[1] = false; int limit = static_cast<int>(std::sqrt(n)); for (int p = 2; p <= limit; ++p) { if (is_prime[p]) { for (int i = p * p; i <= n; i += p) { is_prime[i] = false; } } } for (int i = 2; i <= n; ++i) { if (is_prime[i]) { primes.push_back(i); } } return primes; } int main() { int n; std::cout << "Enter the limit: "; std::cin >> n; std::vector<int> primes = sieve_of_eratosthenes(n); std::cout << "Prime numbers up to " << n << " are:\n"; for (int prime : primes) { std::cout << prime << " "; } std::cout << std::endl; return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.