筛选法求素数

来源:互联网 发布:电视机的网络接口 编辑:程序博客网 时间:2024/06/16 04:34

// 筛选法求素数 CVTE问的一道面试题

#include <iostream>#include <math.h>#include <vector>using namespace std;int main(){    int N = 0;    while( cin >> N )    {        vector<int> data( N + 1, 1 );        for( int i = 2; i <= sqrt( N + 0.0 ); i++ )        {            if( data[i] != 0 )            {                for( int j = 2 * i; j <= N; j += i )                {                    data[j] = 0;                }            }        }        for( int i = 2; i <= N; i++ )        {            if( data[i] != 0 )            {                cout << i << ' ';            }        }        cout << endl;    }    system("pause");    return 0;}
0 0
原创粉丝点击