Factorial calculation【 Array simulation factorial】

Factorial calculation

Description

Enter a positive integer n and output the value of n!.

Where n!=123...n.

Algorithm Description

n! may be very large, and the range of integers that the computer can represent is limited, and high-precision calculation methods are required. Use an array A to represent a large integer a, A[0] represents the ones digit of a, A[1] represents the tens digit of a, and so on.

Multiplying a by an integer k becomes multiplying each element of array A by k. Please pay attention to the corresponding carry.

First set a to 1, then multiply by 2, and multiply by 3. When n is multiplied, the value of n! is obtained.

Input

The input contains a positive integer n, n<=1000.

Output

Output the exact value of n!.

Sample Input 1 

10

Sample Output 1

3628800

Analysis: Just simulate it once.


#include <iostream>
#include <cstdio>
#include <cstring>
#include <bits/stdc++.h>
#include <queue>
#include <algorithm>
#include <map>
#include <cstdlib>
using namespace std;
#define inf 0x3f3f3f3f
int a[100000];
int main()
{
    int n,top,m,temp,tmp;
    scanf("%d", &n);
    top = 0;
    a[top++]=1;
    temp = 0;
    for(int i = 1; i <= n; i ++)
    {
        // 每一位相乘
        for(int j = 0; j < top; j ++)
        {
            temp = temp + a[j] * i;
            a[j] = temp % 10;
            temp = temp / 10;
        }
        // 如果数最高位有进位,进位
        while(temp){
            a[top ++] = temp % 10;
            temp /= 10;
        }

//        for(int i = top-1; i >=0 ; i --)printf("%d",a[i]);printf("\n");
    }
    for(int i = top - 1; i >= 0; i --)
    {
        printf("%d",a[i]);
    }
    printf("\n");
    return 0;
}

> 803 it exploded, I didn't expect it to be wrong. . . .


#include <iostream>
#include <cstdio>
#include <cstring>
#include <bits/stdc++.h>
#include <queue>
#include <algorithm>
#include <map>
#include <cstdlib>
using namespace std;
#define inf 0x3f3f3f3f
int a[100000];
int main()
{
    int n,top,m,temp,tmp;
    scanf("%d", &n);
    top = 0;
    a[top++]=1;
    for(int i = 1; i <= n; i ++)
    {
        for(int j = 0; j < top; j ++)
        {
            temp = a[j] * i;
            if(j == 0)
            {
                a[j] = temp % 10;
                tmp = temp / 10; // tmp 为进位
            }
            else
            {
                temp = temp + tmp;
                a[j] = temp % 10;
                tmp = temp / 10;

            }
            if(j == top - 1)
            {
                if(temp/10>=1)a[top ++] = temp / 10;
                break;

            }

        }
//        for(int i = top-1; i >=0 ; i --)printf("%d",a[i]);printf("\n");
    }
    for(int i = top - 1; i >= 0; i --)
    {
        printf("%d",a[i]);
    }
    printf("\n");
    return 0;
}

 

Guess you like

Origin blog.csdn.net/Mercury_Lc/article/details/107139486