Bestcoder#8 && HDU4990 Reading comprehension(规律)

Reading comprehension

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

点击打开题目链接
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 10 3 100
 

Sample Output
  
  
1 5
 

Source
BestCoder Round #8


╮(╯▽╰)╭将给出的代码优化,否则超时;
题目给出代码是这个样子的,
如果n为奇数,则输出结果是{2^0+2^2+.........................+2^(n-1)}%1000000007;
n为偶数时,输出结果是(2^1+2^3+...........+2^(n-1))%1000000007;
等比数列求和之后就是这个样子的:
n为奇数:(2^(n+1)-1)/3%1000000007;
n为偶数:(2^(n+1)-2)/3%1000000007;
某大神发现了一个神奇的公式:(a/b)%c=(a%(b*c))/b;
其实很好证明的:
设X≡a/b(mod c);
然后神奇的事情发生了,两边同乘以b;
根据同余的性质则有:a≡b*x(mod b*c);
所以结论成立了;
23333333333333333
然后只需要一个快速模取幂就解决啦,好开森。233333333333333
代码:
#include <cstdio>
#include <iostream>
#define MOD 1000000007
using namespace std;
long long m,n;
long long qpow(long long x,long long n){
    long long result=1;
    while (n) {
        if(n&1){
            result*=x;
            result%=3*m;
        }
        x=x*x;
        x%=3*m;
        n=n/2;
    }
    return result;
}
int main()
{
    long long ans;
    while(~scanf("%I64d%I64d",&n,&m))
    {
        ans=0;
        if(n%2)
        {
            ans=qpow(2,n+1)-1;
            ans/=3;
            ans%=MOD;
        }
        else
        {
            ans=qpow(2,n+1)-2;
            ans/=3;
            ans%=MOD;
        }
        printf("%I64d\n",ans%MOD);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值