hdu 4990 Reading comprehension 二分 + 快速幂

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
思路:若n为奇数, ans(n) = 2^(n-1) + 2^(n-3) +...2^0
   若n为偶数, ans(n) = 2^(n-1) + 2^(n-3) +...2^1
 
由于 2^1+2^2+2^3+2^4 = (2^1+2^2) + 2^2*(2^1+2^2)  故只需要算一半就好了, 那么就可以递归处理,注意,若为奇数项,把最后一项算出来加上去就好了
n为奇数时的递归边界是:2^0 = 1;
n为偶数时的递归边界是:2^1 = 2;

  

 
 
 
 
 
 
posted @   JL_Zhou  阅读(333)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示