gpt4 book ai didi

C 用对应于索引的值初始化一个(非常)大的整数数组

转载 作者:太空狗 更新时间:2023-10-29 14:49:58 27 4
gpt4 key购买 nike

Edit3:通过将数组的初始化限制为仅奇数进行优化。谢谢@Ronnie!

Edit2:谢谢大家,看来我也无能为力了。

编辑:我知道 Python 和 Haskell 是用其他语言实现的,并且或多或少地执行了与我下面相同的操作,并且编译的 C 代码将在任何时候击败它们。我只是想知道标准 C(或任何库)是否有内置函数可以更快地执行此操作。

我正在使用 Eratosthenes 算法在 C 中实现素数筛法,并且需要初始化从 0 到 n 的任意大小 n 的整数数组。我知道在 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;
}

有更好的方法吗? (不,显然没有!)

最佳答案

The solution I've come up with initializes the array and then iterates over it, assigning each value to the index at that point, but it feels incredibly inefficient.

你或许可以减少代码行数,但我认为这与“效率”没有任何关系。

虽然在 Haskell 和 Python 中只有一行代码,但幕后发生的事情与您的 C 代码所做的是一样的(在最好的情况下;它的性能可能会更差,具体取决于它的实现方式)。

有标准库函数可以用常量值填充数组(可以想象它们可以表现得更好,尽管我不会打赌),但这在这里不适用。

关于C 用对应于索引的值初始化一个(非常)大的整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17800456/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com