hdu 3123 GCC (2009 Asia Wuhan Regional Contest Online)

本文介绍了一道关于GCC编译器的数学运算优化问题,重点在于如何高效计算一系列阶乘并对特定数值取余,通过直接计算阶乘并取余的方式避免了大数运算导致的时间超时。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GCC

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


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
  
1 10 861017
 

Sample Output
  
593846
 

Source

 

昨天刚开始看到这道题,觉得是一道大数题,开始看到其他人也在做这道题,但是他们都超时了,所以我觉得应该就不是普通的大数题那么简单,后来整理了一下思路,发现了可以优化,如果n>=m的时候,后面的数对m取余得到的结果都是0,所以我们想到可以在这里进行优化,但是还是觉得要用大数题去做,我就套了一个大数阶乘的模板,输入了100000的测试数据进行测试,发现几秒钟都得不出结果,我们就觉得我们的思路有问题就放弃了没去做这道题了,后面看了一下别人的思路,发现我们的那种优化思想还是对的,只不过不要按照那种大数阶乘的思路去做,我们直接一边算阶乘一边进行取余,这样就不会超时了;还是题目做的太少了,很多知识都还不能灵活运用啊,这个题目应该还是可以解决的!

下面是代码:

#include <cstdio>
#include <cstring>
char s[120];
long long m,n,sum,ans;
int main()
{
   int t,len;
   scanf("%d",&t);
   while(t--)
   {
       sum=ans=1;
       scanf("%s%I64d",s,&m);
       len=strlen(s);
       /*if(m==1)//这里是考虑 n=0,m=1的那种情况,直接输出1,
       {
           printf("0\n");
           continue;
       }*/
       if(len>7)
       {
           n=m-1; //当n>=m时,n!对m取余为0
       }
       else
       {
           n=0;
           for(int i=0;i<len;i++)//把字符串转化为数字
           n=n*10+s[i]-'0';
       }
       //求阶乘取余
       for(int i=1;i<=n;i++)
       {
           sum=(sum*i)%m;//求阶乘取余
           ans=(sum+ans)%m;//阶乘和取余
       }
       printf("%I64d\n",ans);//考虑到特殊情况,我们还可以直接再最后进行一次取余运算 ans%m;
   }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值