簡體   English   中英

C使用與索引對應的值初始化一個(非常)大的整數數組

[英]C initializing a (very) large integer array with values corresponding to index

Edit3:通過將數組的初始化限制為僅奇數進行優化。 謝謝@Ronnie!

Edit2:謝謝大家,似乎我無能為力了。

編輯:我知道Python和Haskell是用其他語言實現的,或多或少地執行了與我相同的操作,並且編譯后的C代碼將在任何時候擊敗他們。 我只是想知道標准C(或任何庫)是否具有內置函數來更快地執行此操作。

from 0 to . 我正在使用Eratosthenes的算法在C中實現素數篩,需要初始化一個從0到的任意大小的整數數組。 我知道在Python中您可以執行以下操作:

integer_array = range(n)

就是這樣。 或在Haskell中:

integer_array = [1..n]

但是,我似乎找不到在C中實現的類似方法。我想出的解決方案是初始化數組,然后對其進行迭代,然后在該點將每個值分配給索引,但這種方法效率極低。

int init_array()
{
    /* 
    * assigning upper_limit manually in function for now, will expand to take value for
    * upper_limit from the command line later.
    */
    int upper_limit = 100000000;
    int size = floor(upper_limit / 2) + 1;

    int *int_array = malloc(sizeof(int) * size);
    // debug macro, basically replaces assert(), disregard.    
    check(int_array != NULL, "Memory allocation error");

    int_array[0] = 0;
    int_array[1] = 2;

    int i;

    for(i = 2; i < size; i++) {
        int_array[i] = (i * 2) - 1;
    }

    // checking some arbitrary point in the array to make sure it assigned properly.
    // the value at any index 'i' should equal (i * 2) - 1 for i >= 2
    printf("%d\n", int_array[1000]);  // should equal 1999
    printf("%d\n", int_array[size-1]);  // should equal 99999999

    free(int_array);

    return 0;

error:
    return -1;
}

有一個更好的方法嗎? (不,顯然沒有!)

我想出的解決方案將數組初始化,然后對其進行迭代,然后在該點將每個值分配給索引,但這種方法效率極低。

您也許可以減少代碼行的數量,但是我認為這與“效率”無關。

雖然在Haskell和Python中只有一行代碼,但是在幕后發生的事情與您的C代碼是一樣的(最好的情況;根據實現方式的不同,它的性能可能會更差)。

有一些標准的庫函數可以用常量值填充數組(並且可以想象,它們的性能更好,盡管我不會打賭),但這不適用於這里。

在優化分配方面,更好的算法可能是更好的選擇:-

  1. 利用只需在篩子中測試奇數的事實,將int_array_ptr的大小減半
  2. 通過對數字3、5、7進行車輪分解來運行此操作,以將后續比較減少70%+

那應該加快速度。

暫無
暫無

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

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