すでに述べたように、問題は入力の 1 つがゼロで、ゼロで除算しようとした場合です。積を適切に計算するには、次のような乗算のみを実行し、除算を実行しないアルゴリズムが必要です。
#include <stdio.h>
#include <stddef.h>
// Input: an array of 2^(exp) doubles
// Output: an array of 2^(exp) doubles, where each one is the
// product of all the numbers at different indices in
// the input
// Return value: the product of all inputs
double products (unsigned int exp, const double *in, double *out)
{
if (exp == 0) {
out[0] = 1;
return in[0];
}
size_t half_n = (size_t)1 << (exp - 1);
double prod_left = products(exp - 1, in, out);
double prod_right = products(exp - 1, in + half_n, out + half_n);
for (size_t i = 0; i < half_n; i++) {
out[i] *= prod_right;
out[half_n + i] *= prod_left;
}
return prod_left * prod_right;
}
int main ()
{
double in[8] = {1, 2, 3, 4, 5, 6, 7, 8};
double out[8];
products(3, in, out);
for (size_t i = 0; i < 8; i++) {
printf("%f ", out[i]);
}
printf("\n");
return 0;
}
これには O(n*log(n)) の時間が必要であり、再帰によって使用される O(log(n)) スペースを除いて余分なスペースは必要ありません。これは素晴らしく、理解しやすいものですが、最適ではありません。この質問を参照してください。