大数

来源:互联网 发布:2017优化重组数学答案 编辑:程序博客网 时间:2024/05/21 11:06

原题http://acm.hdu.edu.cn/showproblem.php?pid=3123

GCC

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 3862    Accepted Submission(s): 1268


Problem Description
The GNU Compiler Collection (usually shortened to GCC) is a compiler system produced by the GNU Project supporting various programming languages. But it doesn’t contains the math operator “!”.
In mathematics the symbol represents the factorial operation. The expression n! means "the product of the integers from 1 to n". For example, 4! (read four factorial) is 4 × 3 × 2 × 1 = 24. (0! is defined as 1, which is a neutral element in multiplication, not multiplied by anything.)
We want you to help us with this formation: (0! + 1! + 2! + 3! + 4! + ... + n!)%m


 

Input
The first line consists of an integer T, indicating the number of test cases.
Each test on a single consists of two integer n and m.


 

Output
Output the answer of (0! + 1! + 2! + 3! + 4! + ... + n!)%m.

Constrains
0 < T <= 20
0 <= n < 10^100 (without leading zero)
0 < m < 1000000


 

Sample Input
110 861017


 

Sample Output
593846
//本题需要用到的几个公式(a+b)%m = ((a%m)+(b%m))%m//(a*b)%m = ((a%m)&(b%m))%m//n! = (n-1)!*n;//到n大于等于m的时候起阶乘对m取余为0,所以可以省去。#include <stdio.h>#include <stdlib.h>#include <malloc.h>#include <limits.h>#include <ctype.h>#include <string.h>#include <string>#include <math.h>#include <queue>#include <deque>#include <vector>#include <deque>#include <map>#include <set>#include <algorithm>#include <iostream>using namespace std;#define N 100 + 5char a[N];int main(){    int T,i,j;    int m;    __int64 num;    __int64 sum;    __int64 sum1;    __int64 ans;    __int64 mark;    while(~scanf("%d",&T))    {        while(T--)        {            scanf("%s",a);            scanf("%d",&m);            int len = strlen(a);            if(len <= 7)            {                num = 0;                for(i=0; i<len; i++)                {                    num+=(a[i]-'0')*pow(10,len-i-1);                }                if(num == 0)                {                    ans = 1%m;                    printf("%I64d\n",ans);                    continue;                }                if(num >= m)                {                    num = m-1;                }                mark = 1%m;                sum = mark;                for(i=2;i<=num;i++){                    mark = ((mark%m)*(i%m))%m;                    sum+=mark;                }                ans  = (sum+1)%m;                printf("%I64d\n",ans);            }            else            {                mark = 1%m;                sum = mark;                for(i=2;i<=m-1;i++){                    mark = ((mark%m)*(i%m))%m;                    sum+=mark;                }                ans = (sum+1)%m;                printf("%I64d\n",ans);            }        }    }    return 0;}


 

0 0
原创粉丝点击