【问题标题】:Factorial in D LanguageD语言中的阶乘
【发布时间】:2016-07-28 12:22:07
【问题描述】:

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

【问题讨论】:

  • 我没用过 D lang 但是你有没有参考documentation?它在文档中说了一些关于动态数组here 的内容。

标签: d


【解决方案1】:

在 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]

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


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

【讨论】:

  • @DejanLekic:是的,阶乘实际上是std.range.recurrence 的例子之一。但是,由于某种原因,问题涉及数组。
【解决方案2】:

为什么不使用std.bigint? - 它针对任意精度的数字进行了优化。即使使用ulong (2^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 页面可能对您有所帮助?

【讨论】:

    猜你喜欢
    • 2013-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多