60STL_bitset埃拉托斯特尼筛法demo

60STL_bitset埃拉托斯特尼筛法demo

示例代码

//埃拉托斯特尼筛法:查找质数
#include <iostream>
#include <bitset>
#include <cmath>

using namespace std;

int main()
{
    //用初始化符号()比赋值等号速度快!
    int const max_number(10000000);
    int const max_test((int)sqrt(double(max_number)));   //求算数平方根

    bitset<max_number+1> numbers;   //0不要了,有101个0(0-100)
    numbers.set();  //101个1
    numbers[1] = 0;
    for(int i(1); i != max_test; ++i)
    {
        if(numbers[i])
        {
            for(int j = i*i; j<max_number+1; j+=i)
            {
                numbers[j] = 0;
            }
        }
    }

    cout << "The number of primes less than " << max_number + 1
        << " is " << numbers.count() << ".\n\n";
//    for(int i = 1; i != max_number+1; ++i)
//    {
//        if(numbers[i])
//            cout << i << ", ";
//    }
//    cout << endl;

    return 0;
}

发布了59 篇原创文章 · 获赞 3 · 访问量 1827

猜你喜欢

转载自blog.csdn.net/Felix_hyfy/article/details/98399595