Advertisement
jerimin

display primes

Oct 22nd, 2019
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.15 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7.     const int NUMBER_OF_PRIMES = 50; // Number of primes to display
  8.     const int NUMBER_OF_PRIMES_PER_LINE = 10; // Display 10 per line
  9.     int count = 0; // Count the number of prime numbers
  10.     int number = 2; // A number to be tested for primeness
  11.  
  12.     cout << "The first 50 prime numbers are \n";
  13.  
  14.     // Repeatedly find prime numbers
  15.     while (count < NUMBER_OF_PRIMES)
  16.     {
  17.         // Assume the number is prime
  18.         bool isPrime = true; // Is the current number prime?
  19.  
  20.         // Test if number is prime
  21.         for (int divisor = 2; divisor <= number / 2; divisor++)
  22.         {
  23.             if (number % divisor == 0)
  24.             {
  25.                 // If true, the number is not prime
  26.                 isPrime = false; // Set isPrime to false
  27.                 break; // Exit the for loop
  28.             }
  29.         }
  30.  
  31.         // Display the prime number and increase the count
  32.         if (isPrime)
  33.         {
  34.             count++; // Increase the count
  35.  
  36.             if (count % NUMBER_OF_PRIMES_PER_LINE == 0)
  37.                 // Display the number and advance to the new line
  38.                 cout << setw(4) << number << endl;
  39.             else
  40.                 cout << setw(4) << number;
  41.         }
  42.  
  43.         // Check if the next number is prime
  44.         number++;
  45.     }
  46.  
  47.     return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement