223k views
3 votes
Write a C++ program that prompts the user to enter a positive integer number N, then finds and displays all the primes smaller or equal to N. The program should also count these primes and display the total. To check whether N is a prime or not we need check factors up to sqrt(N) NOT till N, meaning; if no number i in [2, sqrt(n)] is a divisor of N, then N is a prime, otherwise N is not a prime.

User Rzrelyea
by
8.2k points

1 Answer

7 votes

Final answer:

The C++ program takes a positive integer N, finds, and displays all prime numbers less than or equal to N, and counts them by checking factors up to √N for each number.

Step-by-step explanation:

To answer your question, I can provide a C++ program that takes a positive integer N as input and then finds and displays all prime numbers less than or equal to N. The program will also count the number of prime numbers found and display the total count. The prime number checking will be optimized by evaluating factors up to √N (the square root of N) instead of checking all numbers up to N. Let's write the code:


#include
#include
using namespace std;

bool isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) return false;
}
return true;
}

int main() {
int N, count = 0;
cout << "Enter a positive integer number N: ";
cin >> N;

cout << "Prime numbers <= " << N << ": ";
for (int num = 2; num <= N; num++) {
if (isPrime(num)) {
cout << num << " ";
count++;
}
}
cout << "\\Total primes: " << count << endl;
return 0;
}

This is a complete and working C++ program. When executed, it will prompt the user to enter a positive integer and then output the prime numbers less than or equal to that integer. It uses a helper function, isPrime(), to check if a number is prime. Remember to compile the code with a C++ compiler before running it.

User Guto Araujo
by
8.5k points