类似于容器的数组,仅存储大量的1和0

问题描述

我正在尝试编写一个程序,该程序告诉您0到n之间的质数,并告诉您x是否是质数。我设法使其与存储布尔值的非常大的数组一起工作,但是我觉得我可以通过使用位集之类的东西来优化它,但是当我尝试使用位集时,它就会崩溃。我需要该容器能够存储10 ^ 8 0和1。

编辑:对于大量数字,此段错误:(

编辑2: ---示例输入---

9973 6
1
2
3
4
9972
9973

#include <iostream>
#include <algorithm>
#include <bitset>

using namespace std;

int main()
{
    unsigned int n;
    unsigned int x;
    unsigned short int q;

    cin >> n >> q;

    //bitset<10^8 - 1> primes;
    bool primes[n]{false};

    for(unsigned int i = 2; i < n; i++)
    {
        for(unsigned int j = i*i; j < n; j += i)
        {
            primes[j - 1] = true; 
            //primes.set(j - 1);
        }
    }

    primes[0] = true;
    //primes.set(0);
    cout << count(primes,primes + n,false) << endl;
    //cout << primes.count() - 1 << endl;

    for(unsigned short int i = 1; i <= q; i++)
    {
        cin >> x;
        cout << !primes[x - 1] << endl;
    }

    return 0;
} 

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)