⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fig20_40.cpp

📁 经典vc教程的例子程序
💻 CPP
字号:
// Fig. 20.40: fig20_40.cpp                                
// Using a bitset to demonstrate the Sieve of Eratosthenes.
#include <iostream>
#include <iomanip>
#include <bitset>
#include <cmath>

using namespace std;

int main()
{
   const int size = 1024;
   int i, value, counter;
   bitset< size > sieve;

   sieve.flip();

   // perform Sieve of Eratosthenes
   int finalBit = sqrt( sieve.size() ) + 1;

   for ( i = 2; i < finalBit; ++i ) 
      if ( sieve.test( i ) ) 
         for ( int j = 2 * i; j < size; j += i ) 
            sieve.reset( j );

   cout << "The prime numbers in the range 2 to 1023 are:\n";

   for ( i = 2, counter = 0; i < size; ++i )
      if ( sieve.test( i ) ) {
         cout << setw( 5 ) << i;

         if ( ++counter % 12 == 0 ) 
            cout << '\n';
      }            
   
   cout << endl;

   // get a value from the user to determine if it is prime
   cout << "\nEnter a value from 1 to 1023 (-1 to end): ";
   cin >> value;

   while ( value != -1 ) {
      if ( sieve[ value ] )
         cout << value << " is a prime number\n";
      else
         cout << value << " is not a prime number\n";
      
      cout << "\nEnter a value from 2 to 1023 (-1 to end): ";
      cin >> value;
   }

   return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -