阶乘 -C (Linux)

发布于 2024-09-16 05:53:04 字数 617 浏览 1 评论 0原文

请建议我一个更有效的替代方案来执行此计划

#include <stdio.h>

int main(void)
{
    int k, i, t;
    int arr[100]; //Declaring an array

    printf("Enter a positive integer: ");
    scanf("%d", &k);

    for (i = 0; i < k; i++)
    {
        //printf("enter a value %d : ", i);
        scanf("%d", &arr[i]);
    }

    for (i = 0; i < k; i++)
    {
        fact(arr[i]);
    }

}

int fact(int num) // defining function fact(Num)
{

    int i;
    int fact1 = 1;

    for (i = 1; i <= num; i++)
    {
        fact1 = fact1 * i;
    }

    printf("%ld\n", fact1);

}

Please suggest me a more efficient alternative to go about this Program

#include <stdio.h>

int main(void)
{
    int k, i, t;
    int arr[100]; //Declaring an array

    printf("Enter a positive integer: ");
    scanf("%d", &k);

    for (i = 0; i < k; i++)
    {
        //printf("enter a value %d : ", i);
        scanf("%d", &arr[i]);
    }

    for (i = 0; i < k; i++)
    {
        fact(arr[i]);
    }

}

int fact(int num) // defining function fact(Num)
{

    int i;
    int fact1 = 1;

    for (i = 1; i <= num; i++)
    {
        fact1 = fact1 * i;
    }

    printf("%ld\n", fact1);

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

彻夜缠绵 2024-09-23 05:53:04

对于小争论,我同意 Hamish Grubijan 的评论:只需将值制成表格并在运行时查找即可。 n! 的值并不多。以机器编号表示,因此您可以将它们全部制成表格。

n! 的对数通常更有用。当 n! 时,它将适合机器编号。本身就会溢出。请参阅如何计算对数阶乘

For small arguments, I agree with Hamish Grubijan's comment: just tabulate the values and look 'em up at run time. There aren't that many values for which n! is representable in a machine number, so you could tabulate them all.

The logarithm of n! is often more useful. It will fit inside a machine number when n! itself would overflow. See How to compute log factorial.

熊抱啵儿 2024-09-23 05:53:04

您可以使用斯特林公式作为大阶乘的近似值。如果需要非常大的精确阶乘,则需要使用 bignum 算术。渐进最佳效率是通过计算 n! 获得的。从它的质因数分解。如需了解更多算法,请查看

You can use Stirling's formula as an approximation for large factorials. If very large exact factorials are needed, you'll need to use bignum arithmetic. The asymptotically-best efficiency is obtained by computing n! from its prime factorization. For more algorithms, check this

小嗲 2024-09-23 05:53:04

您可以使用斯特林近似来计算大数的阶乘。

You can use Stirling's approximation to calculate the factorial for large numbers.

ゃ懵逼小萝莉 2024-09-23 05:53:04

请参阅快速阶乘函数网站和部分“nofollow noreferrer">阶乘 维基百科文章。

See the Fast Factorial Functions website and to the Computation section of the Factorial Wikipedia article.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文