(Revise Listing, PrimeNumber.cpp) Listing determines whether a number n is prime by checking whether 2, 3, 4, 5, 6,... , n/2 is a divisor. If a divisor is found, n is not prime. A more efficient approach to determine whether n is prime is to check whether any of the prime numbers less than or equal to
can divide n evenly. If not, n is prime. Rewrite Listing to display the first 50 prime numbers using this approach. You need to use an array to store the prime numbers and later use them to check whether they are possible divisors for n.
Listing PrimeNumber.cpp
1 #include
2 #include 3 using namespace std;45 int main()6 {7 NUMBER_OF_PRIMES = 50 ; // Number of primes to display8 const int NUMBER_OF_PRIMES_PER_LINE = 10 ; // Display 10 per line9 int count = 0 ; // Count the number of prime numbers10 int number = 2 ; // A number to be tested for primeness1112 cout << "The first 50 prime numbers are "n" ;1314 // Repeatedly find prime numbers15 while (count bool isPrime = true; // Is the current number prime?1920 // Test if number is prime21 for (int divisor = 2; divisor <= number / 2; divisor++)22 {23 if (number % divisor == 0)24 {25 // If true, the number is not prime26 isPrime = false; // Set isPrime to false27 break; // Exit the for loop28 }29 }3031 // Display the prime number and increase the count32 if (isPrime)33 {34 count++; // Increase the count3536 if (count % NUMBER_OF_PRIMES_PER_LINE == 0)37 // Display the number and advance to the new line38 cout << setw(4) << number < return 0 ;48 }
We need at least 10 more requests to produce the solution.
0 / 10 have requested this problem solution
The more requests, the faster the answer.