简体   繁体   中英

How to directly calculate a series of numbers and store them to a constexpr variable without calculating their size first at compile time?

Is there a way to avoid get_primes_size ? Now the process of calculating primes less than 1000 is repeated twice.

Like first pushing them to a local std::vector , then turning it into a std::array ?

constexpr bool is_prime(int n)
{
    for (int i = 2; i * i < n; i++)
    {
        if (n % i == 0)
        {
            return false;
        }
    }
    return true;
}

template <int upper_limit>
consteval int get_primes_size()
{
    int size = 0;
    for(int i = 2; i <= upper_limit; i++) {
        if (is_prime(i)) {
            size++;
        }
    }
    return size;
}

template <int upper_limit>
consteval auto get_primes()
{
    int count = 0;
    array<int, get_primes_size<upper_limit>()> primes;
    for(int i = 2; i <= upper_limit; i++) {
        if(is_prime(i)) {
            primes[count++] = i;
        }
    }
    return primes;
}

constexpr auto primes = get_primes<1000>();

int main()
{
    cout << "Hello World" << endl;
}

Wouldn't be optimal but since there is for sure less than n/2 primes that are less than n you could just:

array<int, upper_limit/2> primes;

Than in your loop you keep count of the number of primes you encounter the same way you did in get_prime_size and return the truncated array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM