zoukankan      html  css  js  c++  java
  • C语言大数阶乘的求法

     一个朋友问我一个问题100!利用C语言怎么实现。我很当然的写了以下的代码:

    #define     _CRT_SECURE_NO_WARNINGS
    #include     <stdio.h>
    #include     <stdlib.h>
    #include    <string.h>
    
    int main()
    {  
        int  i;
        int N=0;
        int factorial = 1;
        printf("请输入你要的求的阶乘数N\n");
        scanf("%d", &N);
        for (i = 1; i <= N; i++)
        {
            factorial = factorial*i;
        }
        printf("%d!=%d",N,factorial);
       system("pause");
       return 0;
    }

    我输入小数时,结果是没有问题的,但是当我计算100!的时候,发现100!居然是0.这个时候我意识到是不是100!超过我设置的数据类型的范围。但是我发现在C语言中并没有一个数据类型可以容纳100!

    上网查询,我发现可以使用数组来存储大数,原理通俗说就是当一个盒子(内存)无法容纳一个大数,把大数分开放在多个盒子里(数组),把盒子按照顺序输出。

    下面是网上找的一个代码,注释很清楚

    #define     _CRT_SECURE_NO_WARNINGS
    #include     <stdio.h>
    #include     <stdlib.h>
    #include    <string.h>
    
    void factorial(int n, char *pout)
    {
        if (pout == NULL)
        {
            return;
        }
    
        int arr[256];
        int idx = 1;
        arr[0] = 1;
        //此处要注意 i从1开始
        for (int i = 1; i <= n; i++)
        {
            //cry用来记录进位
            int cry = 0;
            // idx记录现在有多少位 挨个相乘
            for (int j = 0; j < idx; j++)
            {
                arr[j] = arr[j] * i + cry;
                //此处用倒序存储
                cry = arr[j] / 10;
                arr[j] %= 10;
            }
            //如果进位大于10 要降级
            while (cry > 10)
            {
                arr[idx++] = cry % 10;
                cry /= 10;
            }
            //进位到这里如果还大于 0 证明位数要加1
            if (cry > 0)
                arr[idx++] = cry;
        }
        //将数组倒序赋值给字符串
        for (int i = idx - 1; i >= 0; i--)
        {
            *pout++ = arr[i] + '0';
        }
        *pout = '\0';
        return;
    }
    
    int main()
    {
        char buff[255] = {0};
        int n = 0;
        printf("input n:");
        scanf("%d", &n);
        factorial(n, buff);
        puts(buff);
        return 0;
    }
  • 相关阅读:
    数值的整数次方
    Grid Sorting
    第K小的数
    图形学变换矩阵的分解
    神经网络理论简介(三)
    神经网络理论简介(二)
    神经网络理论简介(一)
    C/C++的内存对齐
    strcpy的实现
    C++对象模型简析
  • 原文地址:https://www.cnblogs.com/Kroner/p/10813556.html
Copyright © 2011-2022 走看看