簡體   English   中英

如何直接計算一系列數字並將它們存儲到 constexpr 變量而不在編譯時先計算它們的大小?

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

有沒有辦法避免get_primes_size 現在重復兩次計算小於 1000 的素數的過程。

就像先將它們推送到本地std::vector ,然后將其變成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;
}

不會是最佳的,但因為肯定有少於 n/2 個小於 n 的素數,你可以:

array<int, upper_limit/2> primes;

在你的循環中,你會像在get_prime_size中那樣計算你遇到的素數,並返回截斷的數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM