HDU

来源:互联网 发布:王家卫我爱你知乎 编辑:程序博客网 时间:2024/06/06 12:25

Reading comprehension

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1987    Accepted Submission(s): 788


Problem Description
Read the program below carefully then answer the question.
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include<iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include<vector>

const int MAX=100000*2;
const int INF=1e9;

int main()
{
  int n,m,ans,i;
  while(scanf("%d%d",&n,&m)!=EOF)
  {
    ans=0;
    for(i=1;i<=n;i++)
    {
      if(i&1)ans=(ans*2+1)%m;
      else ans=ans*2%m;
    }
    printf("%d\n",ans);
  }
  return 0;
}
 

Input
Multi test cases,each line will contain two integers n and m. Process to end of file.
[Technical Specification]
1<=n, m <= 1000000000
 

Output
For each case,output an integer,represents the output of above program.
 

Sample Input
1 103 100
 

Sample Output
15
 

Source
BestCoder Round #8 
 

分奇偶求通项公式

A(n) = 2 * A(n-1)  + 1(n为奇数)

=> A(n) = 4 * A(n-2) + 1 = 4^2 * A(n-4) + 1 + 4 = 4^3 * A(n-6) + 1 + 4 + 4^2 = . . .  = 4^(n/2) * A(1) + 1 + 4 + 4^2 + ... + 4^(n/2) = 4^(n/2) * A(1) + (4^(n/2) - 1) / 3

A(n) = 2 * A(n-1) (n为偶数)

=> A(n) = 4 * A(n-2) + 2 = 4^2 * A(n-4) + 2 * (1 + 4) = 4^3 * A(n-6) + 2 * (1 + 4 + 4^2) = . . .  = 4^(n/2) * A(1) + 2 * (1 + 4 + 4^2 + ... + 4^(n/2)) = 4^(n/2-1) * A(1) + 2 * (4^(n/2-1) - 1) / 3


#include<iostream>#include<stdio.h>#include<string.h>#define LL long longusing namespace std;LL n,m;LL qkm(LL n,LL m,LL mod){    LL ans = 1,base = n;    while(m)    {        if(m&1)            ans*=base,ans%=mod;        base*=base,base%=mod;        m/=2;    }    return ans;}int main(){    while(scanf("%lld%lld",&n,&m)!=EOF)    {        if(n%2==0)        {            printf("%lld\n",(qkm(4,n/2-1,m)*2%m+2*(qkm(4,n/2-1,m*3)-1)/3)%m);//除法求模可以用乘法逆元来求,不过这里只要除3,比较小,所以直接先对3*m取模就行了        }        else        {            printf("%lld\n",(qkm(4,n/2,m)%m+(qkm(4,n/2,m*3)-1)/3)%m);        }    }    return 0;}