6-10 阶乘计算升级版 (20 分)

本题要求实现一个打印非负整数阶乘的函数。

函数接口定义:

void Print_Factorial ( const int N );

其中N是用户传入的参数,其值不超过1000。如果N是非负整数,则该函数必须在一行中打印出N!的值,否则打印“Invalid input”。

裁判测试程序样例:

#include <stdio.h>

void Print_Factorial ( const int N );

int main()
{
    int N;
	
    scanf("%d", &N);
    Print_Factorial(N);
    return 0;
}

/* 你的代码将被嵌在这里 */

输入样例:

15

输出样例

1307674368000

C 语言提供的数据类型都不足以支持这么大的数据。此算法模拟了手算的过程,用数组来存放结果的每一位。 N 不超过 1000,结果不超过 2600位。所以此算法定义了一个 2600位的数组来存放最终的结果。
提交代码:

void Print_Factorial ( const int N )
{
    if(N < 0)
        printf("Invalid input");
    else
    {
        if(N == 0 || N == 1)
            printf("1");
        else
        {
            int a[2600] = {0};
            a[0] = 1;
            int i,j,k = 1,o = 0;
            for(i = 2; i <= N; i ++)
            {
                for(j = 0; j < k; j ++)
                {
                    int temp;
                    temp = a[j] * i + o;  //o为上一位进上来的数
                    //printf("%d  ",temp);
                    //printf("%d  ",k);
                    a[j] = temp % 10;
                    o = temp / 10;
                    //printf("%d\n",o);
                    if(o && j == k-1)
                        k ++;   //可直接更改for循环里的k值
                }
                //printf("***********\n");
            }
            int p;
            for(p = k - 1; p >= 0; p --)
                printf("%d",a[p]);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42591058/article/details/88935022