D语言中的因子

时间:2016-07-28 12:22:07

标签: d

我刚刚开始使用D并试图在D中编写一个简单的阶乘程序。在D中是否有类似C ++的向量?我想使用向量来创建动态函数来计算阶乘。

2 个答案:

答案 0 :(得分:3)

在D中,动态数组可以调整大小并且可以连接,就像C ++中的向量一样。 以下是此类数组的示例,该数组从stdin读取并写入stdout

import std.stdio;  // for readf and writeln

void main ()  // void for main means "int with return 0 at exit" to OS
{
    int n;
    readf (" %s", &n);  // skip whitespace, then read int in default format
    auto f = [1];  // a dynamic array of int containing a 1
    foreach (i; 1..n + 1)  // for i = 1, 2, 3, ..., n - 1, n
    {
        f ~= f[$ - 1] * i;  // append to f its last element multiplied by i
    }
    writeln (f);  // print the dynamic array in default format
}

输入

10

输出是:

[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]

如评论中所述,有关内置动态数组的更多信息,请参阅the documentation

但是,您提到的动态函数是什么并不清楚。 而且,通常,我们不需要数组或向量来计算阶乘。 检查RosettaCode以了解计算D中的阶乘的其他一些方法。

答案 1 :(得分:2)

为什么不使用std.bigint? - 它针对任意精度数值进行了优化。即使使用ulong2^64),您也只能在20之前计算阶乘,对于此用例,内联表可能更有意义。以下是BigInt的示例:

import std.bigint : BigInt;

BigInt factorial(int n)
{
    auto b = BigInt(1);
    foreach (i; 1..n + 1)
        b *= i;
    return b;
}

void main ()
{
    import std.stdio : writeln;
    factorial(10).writeln; // 3628800
    factorial(100).writeln; // 9.33 * 10^157
}

如果您想了解有关动态数组的更多信息,那么ArraysSlices的DLang Tour页面可能会对您有所帮助吗?