zoukankan      html  css  js  c++  java
  • hdu 3123 GCC (2009 Asia Wuhan Regional Contest Online)

    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
    ");
               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
    ",ans);//考虑到特殊情况,我们还能够直接再最后进行一次取余运算 ans%m;
       }
    }
    


  • 相关阅读:
    VS.NET提示"试图运行项目时出错:无法启动调试。绑定句柄无效"解决办法
    鼠标移动之hook学习
    今天完成任务之SQL中len的使用
    继承(2)方法《.NET 2.0面向对象编程揭秘 》
    框架设计:CLR Via C# 第二章
    启动IIS时提示“服务没有及时响应启动或控制请求”几种解决方法
    C#中处理字符串和数字
    TreeView实现权限管理
    鼠标单击右击双击简单功能的实现
    richTextBox 中插入图片
  • 原文地址:https://www.cnblogs.com/blfshiye/p/5397808.html
Copyright © 2011-2022 走看看