sdut 简单GCC

来源:互联网 发布:网站源码可以干什么 编辑:程序博客网 时间:2024/06/16 22:41

这道题看起来是很复杂,一开始竟然想到转换成矩阵相乘然后利用快速幂进行优化从而求解,但是想来想去越来越复杂,最后发现一个简单的结论。

n>m时直接取n=m即可,因为比较大的阶乘中始终会有m,这样无论n多大,总是呢个能够找到一使取模之后的结果为0,所以直接暴力跑一边遍就可以求解。

#include<cstdio>#include<iostream>#include<cstring>#include<algorithm>using namespace std;long long n,m;char a[105];void solve(){    long long res=1,num=1,i;    if(strlen(a)>6)        n=m;    else    {        for(i=n=0;a[i];i++)            n=n*10+a[i]-'0';        if(n>m)            n=m;    }    for(i=1;i<=n;i++)    {        num=(num*i)%m;        res=(res+num)%m;    }    printf("%lld\n",res%m);}int main(){    int t;    scanf("%d",&t);    while(t--&&scanf("%s%lld",a,&m)!=EOF)        solve();    return 0;}



GCC

Time Limit: 1000MS Memory Limit: 65536KB
SubmitStatistic Discuss

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. 

0 < T <= 20
0 <= n < 10100 (without leading zero)
0 < m < 1000000 

Output

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

Example Input

1 10 861017 

Example Output

593846


0 0
原创粉丝点击