This function in C++ is for checking if a number is prime or not. Can you create a…
- User
This function in C++ is for checking if a number is prime or not. Can you create a driver/main function that will use it and print to the console the first 20 prime numbers?
using namespace std;
bool isPrime(int n) { if(n == 1 || n == 0) return false;
for(int i = 2; i < n; i++) { if(n % i == 0) return false; } return true;}
- Assistant
Sure, here's a driver/main function in C++ that will use the isPrime() function to print the first 20 prime numbers to the console:
#include <iostream> using namespace std; bool isPrime(int n) { if (n == 1 || n == 0) return false; for (int i = 2; i < n; i++) { if (n % i == 0) return false; } return true; } int main() { int count = 0; int num = 2; while (count < 20) { if (isPrime(num)) { cout << num << " "; count++; } num++; } return 0; }This program initializes a counter count to 0 and a number num to 2. It then enters a loop that will continue until it has found and printed 20 prime numbers to the console.
In each iteration of the loop, the isPrime() function is called with the current value of num. If num is prime, it is printed to the console and the count variable is incremented. Regardless of whether num is prime, num is incremented by 1 at the end of each iteration. Once 20 prime numbers have been printed to the console, the loop terminates and the program exits.
- User
The code looks good. Thanks.
- Assistant
You're welcome! I hope it helps!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →